博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA——利用wait和notify实现生产者和消费者
阅读量:7129 次
发布时间:2019-06-28

本文共 2444 字,大约阅读时间需要 8 分钟。

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

注意事项:

  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
pool=new Vector
(); 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 @Override27 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 block34 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 @Override61 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 block68 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 }

执行结果是:

转载于:https://www.cnblogs.com/pin-wang/p/5521689.html

你可能感兴趣的文章
TurboMail为企业提供海量投递邮件群发系统
查看>>
Linux系统命令Cut使用
查看>>
我的友情链接
查看>>
chrome 跨域设置-(完善博客内容)
查看>>
12月8日学习内容整理:ORM中的创建多表关系,基于多表关系的插入记录,基于对象的跨表查询...
查看>>
利用nginx实现负载均衡
查看>>
【EXCRT模板】POJ2891/LuoGu4777Strange Way to Express Integers拓展中国剩余定理
查看>>
Python基础24_正则表达式,re模块,
查看>>
mysql 开源 ~ canal+otter系列(2)
查看>>
跟我一起写 Makefile (Linux )
查看>>
CC2640R2F&TI-RTOS 拿到 TI CC2640R2F 开发板 第二件事就是 LED 驱动 ,点个灯
查看>>
ELASTIC SEARCH 性能调优
查看>>
Java并发总结(三):中断线程
查看>>
Beer Refrigerator
查看>>
hadoop输入分片计算(Map Task个数的确定)
查看>>
TYVJ P1008 传球游戏
查看>>
MVC基础
查看>>
【BZOJ】 Hash Killer I II III
查看>>
为什么st2 chrome无法显示api中的例子
查看>>
setPreferredSize的用法
查看>>