|
import java.util.concurrent.locks.*;
class MealCS {
private final int orderNum;
public MealCS(int num) {
this.orderNum=num;
}
public String toString() {
return " MealCS "+orderNum;
}
}
class WaitPersonCS implements Runnable {
private Lock lock;
private Condition condition;
private int count;
public WaitPersonCS(Lock lock,Condition condition,int count) {
this.lock=lock;
this.condition=condition;
this.count=count;
}
public void run() {
try {
while(count-->0) {
lock.lock();
try{
while(RestaurantCS.MEAL==null)
condition.await();
System.out.println("The WaitPersonCS has eaten " + RestaurantCS.MEAL);
RestaurantCS.MEAL=null;
condition.signal();
}finally{
lock.unlock();
}
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
class ChefCS implements Runnable {
private Lock lock;
private Condition condition;
private int count;
public ChefCS(Lock lock,Condition condition,int count) {
this.lock=lock;
this.condition=condition;
this.count=count;
}
public void run() {
try {
while(count-->0) {
lock.lock();
try{
while(RestaurantCS.MEAL!=null)
condition.await();
RestaurantCS.MEAL=new MealCS(count);
System.out.println("The ChefCS has made " + RestaurantCS.MEAL);
condition.signal();
}finally{
lock.unlock();
}
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public class RestaurantCS {
public static MealCS MEAL;
public static void main(String[] args) throws Exception {
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();
new Thread(new ChefCS(lock,condition,10)).start();
new Thread(new WaitPersonCS(lock,condition,10)).start();
}
} |
|
|