public class ThreadCommunication{
public static void main(String[] args) { Queue q = new Queue();//创建,并初始化一个队列 Thread p1 = new Thread(new Product(q));
Thread c1 = new Thread(new Consumer(q)); c1.start();
p1.start();
}
} class Product implements Runnable { Queue q ; //声明队列
public Product(Queue q) {
this.q = q;
} public void run() {
for(int i=1; i<5;i++){
q.put(i);
}
}
}
class Consumer implements Runnable { Queue q ; //声明队列
public Consumer(Queue q) {
this.q = q;
} public void run() {
while(true){
q.get();//循环消费,每次消费了一个元素
}
}
} class Queue {
int value = 0;
boolean isEmpty = true;
//生产方法
public synchronized void put(int v){
if(!isEmpty){
System.out.println("共享数据没有被消费,生产者等待...");
try {
wait();//进入等待状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
value += v;
isEmpty = false; //不为空了
System.out.println("生产者产品数量:"+value);
notify();//通知消费者
}
//消费方法
public synchronized int get(){ if(isEmpty){
try {
System.out.println("共享数据为空,消费者等待...");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
value--;
if(value < 1){
isEmpty = true;
}
System.out.println("消费者消费了一个,剩余:"+value);
notify();
return value;//返回剩余的产品总数
}
}
运行结果: