生产者消费者,单单
package star20110712;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;public class Restaurant {Meal meal;ExecutorService executorService = Executors.newCachedThreadPool();Waiter waiter = new Waiter(this);Chef chef = new Chef(this);//List<Waiter> waiters;//List<Chef> chefs;public Restaurant() {//waiters = new ArrayList<Waiter>();//chefs = new ArrayList<Chef>();////for(int i= 0;i<5;i++){//Waiter waiter = new Waiter(this);//waiters.add(waiter);//Chef chef = new Chef(this);//chefs.add(chef);//}executorService.execute(waiter);executorService.execute(chef);}public static void main(String[] args) {new Restaurant();}}class Meal{//用final修饰,在多线程中,可以增加其值private final int orderNum;public Meal(int orderNum) {this.orderNum = orderNum;}@Overridepublic String toString() {return "Meal:"+orderNum;}}class Waiter implements Runnable{private Restaurant restaurant;public Waiter(Restaurant restaurant) {this.restaurant = restaurant;}@Overridepublic void run() {try {while(!Thread.interrupted()){synchronized(this){while(restaurant.meal == null){wait();}}System.out.println("Waiter got:"+restaurant.meal);synchronized (restaurant.chef) {restaurant.meal = null;//restaurant.chef.notifyAll();restaurant.chef.notify();}}} catch (InterruptedException e) {System.out.println("服务员终止");}}}class Chef implements Runnable{private Restaurant restaurant;private int count = 0;public Chef(Restaurant restaurant) {this.restaurant = restaurant;}@Overridepublic void run() {try {while(!Thread.interrupted()){synchronized(this){while(restaurant.meal != null){wait();}}System.out.println("开始销售了第"+count+"个");if(++count == 10){System.out.println("销售完了");restaurant.executorService.shutdownNow();}synchronized(restaurant.waiter){restaurant.meal = new Meal(count);//restaurant.waiter.notifyAll();restaurant.waiter.notify();}TimeUnit.SECONDS.sleep(1);}} catch (InterruptedException e) {System.out.println("厨师终止");}}}
?只是单消费者,单供应者。思考多消费者时,每一位消费者,相当于每一位服务员,那么一个服务员是不是考虑一个线程?
那么在唤醒的时候使用NotifyAll(),为什么API里没有Executors执行一个Runnable数组呢,或者list。