62,614
社区成员
发帖
与我相关
我的任务
分享
package com.imooc;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Meal{
private final int id;
Meal(int id){
this.id=id;
}
public String toString(){
return "Meal: "+id;
}
}
class Cook implements Runnable{
private LinkedList<Meal> mealList;
private static int count;
Cook(LinkedList<Meal> mealList){
this.mealList=mealList;
}
public void run(){
while(!Thread.interrupted()){
synchronized(mealList){
while(mealList.size()<5){
System.out.print("厨师正在做这个菜:");
System.out.println(++count);
mealList.add(new Meal(count));
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mealList.notifyAll();
while(mealList.size()==5){
System.out.println("厨师正在等服务员端走菜");
try {
mealList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
System.out.println("厨师下班了");
}
}
class Waiter implements Runnable{
private LinkedList<Meal> mealList;
Waiter(LinkedList<Meal> mealList){
this.mealList=mealList;
}
public void run(){
while(!Thread.interrupted()){
synchronized(mealList){
while(mealList.size()>0){
System.out.println("服务员正在端走这个菜:"+mealList.getLast());
mealList.removeLast();
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mealList.notifyAll();
while(mealList.size()==0){
System.out.println("服务员正在等厨师做菜");
try {
mealList.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
System.out.println("服务员下班了");
}
}
public class Manager {
public static void main(String args[]) {
LinkedList<Meal> mealList = new LinkedList<Meal>();
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Waiter(mealList));
exec.execute(new Cook(mealList));
exec.execute(new Waiter(mealList));
exec.execute(new Waiter(mealList));
exec.execute(new Cook(mealList));
exec.shutdown();
}
}