public class Test {
public static void main(String[] args){
Object mutex = new Object();
new Producer(mutex).start();
new Consumer(mutex).start();
}
static class Product{
public volatile static String value = null;
}
static class Consumer extends Thread{
private Object mutex;
public Consumer(Object mutex) {
this.mutex = mutex;
}
@Override
public void run() {
//一直消费产品
while (true){
synchronized (mutex){
//如果还没生产出产品 等待生产出产品
if (null == Product.value){
// System.out.println("consumer :"+Product.value);
// Product.value = null;
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//使用
System.out.println("consumer :"+Product.value);
Product.value = null;
//通知生产者 可以生产了
mutex.notify();
}
}
}
}
static class Producer extends Thread{
private Object mutex;
public Producer(Object mutex) {
this.mutex = mutex;
}
@Override
public void run() {
//生产 产品
while (true){
synchronized (mutex){
//如果没有产品就生产
if (null != Product.value){
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Product.value = "NO:"+System.currentTimeMillis();
System.out.println("producer ");
//通知消费者 可以消费了
mutex.notify();
}
}
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4414/viewspace-2812642/ ,如需转载,请注明出处,否则将追究法律责任。