生产者消费者,单单

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;
	}
	@Override
	public String toString() {
		return "Meal:"+orderNum;
	}
}

class Waiter implements Runnable{
	private Restaurant restaurant;
	public Waiter(Restaurant restaurant) {
		this.restaurant = restaurant;
		}
	@Override
	public 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;
	}
	@Override
	public 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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值