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

Posted JackerWang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA——利用wait和notify实现生产者和消费者相关的知识,希望对你有一定的参考价值。

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

注意事项:

  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实现生产者和消费者的主要内容,如果未能解决你的问题,请参考以下文章

JAVA笔记(20)--- 死锁;如何解决线程安全问题;守护线程;定时器;Callable 实现线程;wait ( ) 和 notify ( ) ;实现生产者和消费者模式;

基于线程实现的生产者消费者模型(Object.wait(),Object.notify()方法)

(二)线程状态、wait/notify

Java多线程基础-第一节5:wait和notify

Java线程间通信之wait/notify

从Guarded Block来看Java中的wait和notify方法