java经典例题:生产者/消费者问题

编程入门 行业动态 更新时间:2024-10-17 07:26:00

java经典<a href=https://www.elefans.com/category/jswz/34/1767926.html style=例题:生产者/消费者问题"/>

java经典例题:生产者/消费者问题

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();
/*
生产者生产了一件商品  
消费者购买了一件商品    
生产者生产了一件商品  
消费者购买了一件商品  
生产者生产了一件商品  
消费者购买了一件商品  
生产者生产了一件商品  
消费者购买了一件商品
......
*/

更多推荐

java经典例题:生产者/消费者问题

本文发布于:2023-11-16 13:10:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:例题   生产者   消费者   经典   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!