已解决
java经典例题:生产者/消费者问题
来自网友在路上 192892提问 提问时间:2023-11-05 18:59:47阅读次数: 92
最佳答案 问答题库928位专家为你答疑解惑
java经典例题:生产者/消费者问题
●生产者(Productor)将产品放在柜台(Counter),而消费者(Customer)从柜台
处取走产品,生产者一次只能生产固定数量的产品(比如:1), 这时柜台中不能
再放产品,此时生产者应停止生产等待消费者拿走产品,此时生产者唤醒消费者来
取走产品,消费者拿走产品后,唤醒生产者,消费者开始等待.
Counter:
public class Counter {int num=0;//代表商品数//锁对象是this,add()和sub()用同一把锁//生产商品public synchronized void add(){if(num==0){System.out.println("生产者生产了一件商品 ");num=1;//生产者生产了一件商品this.notify();//唤醒消费者}else {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}}//卖出商品public synchronized void sub(){if(num>0){System.out.println("消费者购买了一件商品 ");num=0;//消费者拿走了商品this.notify();//唤醒生产者}else {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}}
}
ProductorThread:
public class ProductorThread extends Thread{Counter counter;ProductorThread(Counter counter){this.counter=counter;//把测试中的counter放入线程中使用}@Overridepublic void run() {while (true) {counter.add();}}
}
CustomerThread:
public class CustomerThread extends Thread{Counter counter;CustomerThread(Counter counter){this.counter=counter;//把测试中的counter放入线程中使用}@Overridepublic void run() {while (true) {counter.sub();}}
}
Test:
Counter counter=new Counter();ProductorThread productorThread=new ProductorThread(counter);CustomerThread customerThread=new CustomerThread(counter);productorThread.start();customerThread.start();
/*
生产者生产了一件商品
消费者购买了一件商品
生产者生产了一件商品
消费者购买了一件商品
生产者生产了一件商品
消费者购买了一件商品
生产者生产了一件商品
消费者购买了一件商品
......
*/
查看全文
99%的人还看了
相似问题
- rabbitMQ的扇出模式(fanout发布订阅)的生产者与消费者使用案例
- Java编写简易rabbitmq生产者与消费者
- SpringBoot Kafka生产者 多kafka配置
- linux入门---消费者生产者模型模拟实现
- java经典例题:生产者/消费者问题
- RocketMQ生产者消息发送出去了,消费者一直接收不到怎么办?(Rocket MQ订阅关系一致性)
- <多线程章节九>生产者消费者模型,阻塞队列的使用和模拟实现
- Spring Kafka生产者实现
- Sentinel学习(2)——sentinel的使用,引入依赖和配置 对消费者进行流控 对生产者进行熔断降级
- 【Linux】生产者和消费者模型
猜你感兴趣
版权申明
本文"java经典例题:生产者/消费者问题":http://eshow365.cn/6-32917-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: C#when关键字
- 下一篇: 【数据结构】单链表详解(超详细)