问题描述:有一个这样的饭店,他有一个厨师和服务员。这个服务员必须等待厨师准备好膳食。当厨师准备好时,他会通知服务员,之后服务员上菜,然后返回继续等待。
代码如下:
package concurrency;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Meal{
private final int id;
public Meal(int id){
this.id = id;
}
public String toString(){
return "Meal: " + id;
}
}
class WaitMan implements Runnable{
private Restaurant restaurant;
public WaitMan(Restaurant restaurant){
this.restaurant = restaurant;
}
public void run() {
try {
while (!Thread.interrupted()) {
synchronized (this) {
while (restaurant.meal == null) {
wait();
}
}
System.out.println("Waitman got " + restaurant.meal);
synchronized (restaurant.chef) {
restaurant.meal = null;
restaurant.chef.notifyAll();
}
}
} catch (InterruptedException e) {
System.out.println("WaitMan intettupted");
}
}
}
class Chef implements Runnable{
private Restaurant restaurant;
private int count = 0;
public Chef(Restaurant restaurant){
this.restaurant = restaurant;
}
public void run(){
try {
while(!Thread.interrupted()){
synchronized (this) {
while(restaurant.meal != null){
wait();
}
}
}
if(++count == 10){
System.out.println("Out of food, closing");
restaurant.exec.shutdownNow();
System.exit(0);
}
System.out.println("Order up!");
synchronized (restaurant.waitMan) {
restaurant.meal = new Meal(count);
restaurant.waitMan.notifyAll();
}
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
System.out.println("Chef intettupted");
}
}
}
public class Restaurant {
Meal meal;
WaitMan waitMan = new WaitMan(this);
Chef chef = new Chef(this);
ExecutorService exec = Executors.newCachedThreadPool();
public Restaurant(){
exec.execute(chef);
exec.execute(waitMan);
}
public static void main(String[] args) {
new Restaurant();
}
}
代码运行不出结果,貌似出现了死锁,求大神赐教