java多线程之生产者消费者模型

 1 public class ThreadCommunication{
 2     public static void main(String[] args) {
 3         
 4         Queue q = new Queue();//创建,并初始化一个队列
 5         
 6         Thread p1 = new Thread(new Product(q));
 7         Thread c1 = new Thread(new Consumer(q));
 8         
 9         c1.start();
10         p1.start();
11     }
12 }
13 
14 class Product implements Runnable {
15     
16     Queue q ; //声明队列
17     public Product(Queue q) {
18         this.q = q;
19     }
20 
21     public void run() {
22         for(int i=1; i<5;i++){
23             q.put(i);
24         }
25     }
26 }
27 class Consumer implements Runnable {
28     
29     Queue q ; //声明队列
30     public Consumer(Queue q) {
31         this.q = q;
32     }
33 
34     public void run() {
35         while(true){
36             q.get();//循环消费,每次消费了一个元素
37         }
38     }
39 }
40 
41 class Queue {
42     int value = 0;
43     boolean isEmpty = true;
44     //生产方法
45     public synchronized void put(int v){
46         if(!isEmpty){
47             System.out.println("共享数据没有被消费,生产者等待...");
48             try {
49                 wait();//进入等待状态
50             } catch (InterruptedException e) {
51                 e.printStackTrace();
52             }
53         }
54         value += v;
55         isEmpty = false; //不为空了
56         System.out.println("生产者产品数量:"+value);
57         notify();//通知消费者
58     }
59     //消费方法
60     public synchronized int get(){
61         
62         if(isEmpty){
63             try {
64                 System.out.println("共享数据为空,消费者等待...");
65                 wait();
66             } catch (InterruptedException e) {
67                 e.printStackTrace();
68             }
69         }
70         value--;
71         if(value < 1){
72             isEmpty = true;
73         }
74         System.out.println("消费者消费了一个,剩余:"+value);
75         notify();
76         return value;//返回剩余的产品总数
77     }
78 }

运行结果:

 

posted @ 2017-11-23 14:13  潸然  阅读(279)  评论(0编辑  收藏  举报