码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA——利用wait和notify实现生产者和消费者

时间:2016-05-24 00:11:06      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

经典的消费者和生产者的的实现:

注意事项:

  1:在循环里面用wait(),因为当线程获得了锁,但是有可能还没有满足其他条件:

  2:公用的缓冲池要用锁机制:

 

 1 package demo;
 2 
 3 import java.util.Vector;
 4 
 5 public class Main {
 6 
 7     public static void main(String[] args) {
 8         Vector<Integer> pool=new Vector<Integer>();
 9         Producer producer=new Producer(pool, 4);
10         Consumer consumer=new Consumer(pool);
11         new Thread(producer).start();
12         new Thread(consumer).start();
13     }
14 
15 }
16 
17 //生产者
18 class Producer implements Runnable{
19     private Vector pool;
20     private Integer size;
21     
22     public Producer(Vector pool, Integer size) {
23         this.pool = pool;
24         this.size = size;
25     }
26     @Override
27     public void run() {
28         for(int i=0;i<7;i++){
29             try {
30                 System.out.println("produce "+i);
31                 produce(i);
32             } catch (InterruptedException e) {
33                 // TODO Auto-generated catch block
34                 e.printStackTrace();
35             }
36         }
37     }
38     private void produce(int i) throws InterruptedException{
39         while(pool.size()==size){
40             synchronized (pool) {
41                 System.out.println("pool is full Producer is waiting,size is "+pool.size());
42                 pool.wait();
43             }
44         }
45         synchronized (pool) {
46             pool.add(i);
47             pool.notifyAll();
48         }
49     }
50 }
51 
52 
53 //消费者
54 class Consumer implements Runnable{
55     private Vector pool;
56     public Consumer(Vector pool) {
57         this.pool = pool;
58     }
59     
60     @Override
61     public void run() {
62         for(int i=0;i<7;i++){
63             try {
64                 System.out.println("consume "+i);
65                 consume();
66             } catch (InterruptedException e) {
67                 // TODO Auto-generated catch block
68                 e.printStackTrace();
69             }
70         }
71     }
72     
73     private void consume() throws InterruptedException{
74         while(pool.isEmpty()){
75             synchronized (pool) {
76                 System.out.println("pool is empty Consumer is waiting,size is "+pool.size());
77                 pool.wait();
78             }
79         }
80         synchronized (pool) {
81             pool.notifyAll();
82             pool.remove(0);
83             
84         }
85     }
86 }
技术分享

执行结果是:

技术分享

JAVA——利用wait和notify实现生产者和消费者

标签:

原文地址:http://www.cnblogs.com/pin-wang/p/5521689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!