写一段生产者、消费者的程序:
//资源
class Meal {
private final int orderNum;
public Meal(int orderNum) {
this.orderNum = orderNum;
}
@Override
public String toString() {
return "Meal " + orderNum;
}
}
//服务生 消费者
class WaitPerson implements Runnable {
private Restaurant restaurant;
public WaitPerson(Restaurant restaurant) {
this.restaurant = restaurant;
}
@Override
public void run() {
try {
while(!Thread.interrupted()) {
synchronized(this) {
while(restaurant.meal == null) {
this.wait();
}
}
System.out.println("WaitPerson got " + restaurant.meal);
synchronized(restaurant.chef) {
restaurant.meal = null;
restaurant.chef.notify();
}
}
} catch(InterruptedException e) {
System.out.println("WaitPerson Interrupted");
}
}
}
//厨师 生产者
class Chef implements Runnable {
private int count = 0;
private Restaurant restaurant;
public Chef(Restaurant restaurant) {
this.restaurant = restaurant;
}
@Override
public void run() {
try {
while(!Thread.interrupted()) {
synchronized(this) {
while(restaurant.meal != null) {
this.wait();
}
}
if(++count == 10) {
System.out.println("System Quit");
restaurant.exec.shutdownNow();
System.exit(0);
}
System.out.print("Order up! ");
synchronized(restaurant.waitPerson) {
restaurant.meal = new Meal(count);
restaurant.waitPerson.notify();
}
TimeUnit.MILLISECONDS.sleep(100);
}
} catch(InterruptedException e) {
System.out.print("Chef Interrupted");
}
}
}
//餐馆
public class Restaurant {
Meal meal;
WaitPerson waitPerson = new WaitPerson(this);
Chef chef = new Chef(this);
ExecutorService exec = Executors.newCachedThreadPool();
public Restaurant() {
exec.execute(waitPerson);
exec.execute(chef);
}
public static void main(String[] args) {
new Reataurant();
}
}
看看哪有错。。。应该没错