生产者消费者模型:
实现手段 用wait(),notifALL()实现;
问题描述:在一个餐馆里,有一个厨师(做食物),有一个伙计(端食物/消费);
食物为空时:伙计不能再端食物,此时通知厨师要做菜;
食物不为空时: 厨师就不再做食物,通知伙计消费食物;
//此处问题抽象:厨师每次只能做一样食物(只有一个盘子),可以做多次;
食物类:
class Meal1{
static int cnt;
Meal1(int i){cnt=i;}
@Override
public String toString() {
return "第"+cnt+"盘"+"食物";
}
}
伙计类:
class WaitPerson1 implements Runnable{
private Restaurant1 restaurant1;
WaitPerson1(Restaurant1 restaurant){
this.restaurant1=restaurant;
}
public void run() {
try {
while(!Thread.interrupted())
{ //餐馆食物为空时:伙计等待
synchronized(this)
{
while(this.restaurant1.meal1==null){
this.wait();
}
}
//食物不为空才能执行以下语句;
System.out.println("消费掉:"+this.restaurant1.meal1+"!");
synchronized(this.restaurant1.chef1){
this.restaurant1.meal1=null; //消费食物
this.restaurant1.chef1.notifyAll(); //通知厨师工作
}
}
} catch (InterruptedException e) {
System.out.println("伙计打断操作!");
e.printStackTrace();
}
}
}
厨师类:
class Chef1 implements Runnable{
private Restaurant1 restaurant1;
Chef1(Restaurant1 restaurant){
this.restaurant1=restaurant;
}
public void run() {
try {
while(!Thread.interrupted())
{ //餐馆食物为不为空时:厨师等待
synchronized(this)
{
while(this.restaurant1.meal1!=null){
this.wait();
}
}
//食物为空才能执行以下语句;
if(++Meal1.cnt==11){ //一共上10盘食物 ,超过后打断线程
this.restaurant1.exec.shutdownNow();
}
synchronized(this.restaurant1.waitPerson1){
this.restaurant1.meal1=new Meal1(Meal1.cnt);//生成新食物并编号
this.restaurant1.waitPerson1.notifyAll();//通知伙计工作
}
}
} catch (InterruptedException e) {
System.out.println("厨师打断操作!");
e.printStackTrace();
}
}
}
餐馆类:
class Restaurant1 {
Meal1 meal1;
//此处必须传入this指针不可以新生成;因为在逻辑下只有一个餐馆;
Chef1 chef1 = new Chef1(this);
WaitPerson1 waitPerson1 = new WaitPerson1(this);
ExecutorService exec = Executors.newCachedThreadPool();
public Restaurant1() {
exec.execute(chef1);
exec.execute(waitPerson1);
}
}
测试:
public class TestRestaurant {
public static void main(String[] args) {
new Restaurant1();
}
}
结果: