生产者与消费者模型,使用合理的线程池来实现10个生产者与5个消费者并发处理商品的售卖。
import java.util.ArrayList;
import java.util.List;
class Goods{
//产品名称
private String name;
//产品数量
private int count;
//生产方法
public synchronized void set(String name) throws InterruptedException {
while(count>0) {
wait();
}
this.name=name;
this.count=count+1;
System.out.println(toString());
notify();
}
//消费方法
public synchronized void get() throws InterruptedException {
while(count==0) {
wait();
}
this.count=this.count-1;
System.out.println(toString());
notify();
}
@Override
public String toString() {
return Thread.currentThread().getName()+"产品:"+name+" "+"数量为:"+count;
}
}
//生产者类
class Producer implements Runnable{
private Goods goods;
public Producer(Goods goods) { //生产者的构造方法是为了限制传入的参数是Good类的对象,使得生产者消费者都是用的是GOOD对象
super();
this.goods=goods;
}
@Override
public void run() {
while(true) {
try {
this.goods.set("代码一段");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//消费者类
class Cusumer implements Runnable{
private Goods goods;
public Cusumer(Goods goods) {
super();
this.goods=goods;
}
@Override
public void run() {
while(true) {
try {
this.goods.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ShengChanXiaoFeiZhe {
public static void main(String[] args) {
List<Thread> list=new ArrayList<>();
Goods goods=new Goods();
//十个消费者线程
for(int i=0;i<10;i++) {
Producer producer=new Producer(goods);
Thread thread=new Thread(producer,"消费者-"+i);
list.add(thread);
}
for(int i=0;i<5;i++) {
Cusumer cusumer=new Cusumer(goods);
Thread thread=new Thread(cusumer,"生产者-"+i);
list.add(thread);
}
for(Thread thread :list) {
thread.start();
}
}
}