700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > JAVA——利用wait和notify实现生产者和消费者

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

时间:2018-12-09 22:02:45

相关推荐

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

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

注意事项:

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

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

1 package demo; 2 3 import java.util.Vector; 4 5 public class Main { 6 7public 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{19private Vector pool;20private Integer size;2122public Producer(Vector pool, Integer size) {23 this.pool = pool;24 this.size = size;25}26@Override27public 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 block34 e.printStackTrace();35 }36 }37}38private 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{55private Vector pool;56public Consumer(Vector pool) {57 this.pool = pool;58}5960@Override61public 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 block68 e.printStackTrace();69 }70 }71}7273private 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 }

执行结果是:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。