当前位置:首页 > 编程笔记 > 正文
已解决

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%的人还看了

猜你感兴趣

版权申明

本文"java经典例题:生产者/消费者问题":http://eshow365.cn/6-32917-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!