import java.util.LinkedList;
import java.util.List;
import java.util.Random;
public class TestProducerAndConsumer {
public static void main(String[] args) {
Store s = new Store();//仓库对象
Thread p1 = new Producer( s );
Thread p2 = new Producer( s );
Thread c1 = new Consumer( s );
Thread c2 = new Consumer( s );
p1.start();//生产者线程
p2.start();//生产者线程
c1.start();//消费者线程
c2.start();//消费者线程
}
}
//生产者消费者模式
//生产者与消费者操作同一个容器,当生产者生产的商品到达一定容量时不再生产,消费者当商品完毕后不再消费
//生产者每生产一个商品就可以通知消费者进行消费
//消费者每消费一个商品都可以通知生产者生产
class Producer extends Thread{
private Store s;
public Producer(Store s){
this.s = s;
}
public void run(){
while(true){
synchronized( s ){
while(s.getCount() == Store.MAX_COUNT){//如果商品数量==仓库最大容量
try{s.wait();}catch(Exception e){}//进入等待队列并释放锁标记
}
System.out.print(super.getName()+"\t");//为了打印效果
s.addProduct();//生产商品
s.notifyAll();
}
try{Thread.sleep(new Random().nextInt(300));}catch(Exception e){}//为了打印效果
}
}
}
class Consumer extends Thread{
private Store s;
public Consumer(Store s){
this.s = s;
}
public void run(){
while(true){
synchronized( s ){
while(s.getCount()==0){
try{s.wait();}catch(Exception e){}//进入等待队列并释放锁标记
}
System.out.print(super.getName()+"\t");//为了打印效果
s.getProduct();//消费商品
s.notifyAll();
}
try{Thread.sleep(new Random().nextInt(300));}catch(Exception e){}//为了打印效果
}
}
}
class Store{//仓库--负责存储商品
private List<String> list = new LinkedList<String>();
public static final Integer MAX_COUNT = 10;//最大仓库容量
//添加商品
public void addProduct(){
list.add("❤");
System.out.println("生产者:"+list);
}
//获取商品
public void getProduct(){
list.remove(0);
System.out.println("消费者:"+list);
}
//获取仓库中的商品数量
public int getCount(){
return list.size();
}
}
N个生产者N个消费者问题
最新推荐文章于 2021-11-19 16:58:28 发布