线程间的协作(2)——生产者与消费者

1.何为生产者与消费者

    在线程世界里,生产者就是生产数据的线程,消费者就是消费数据的线程。


import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName:Restraurant
 * @Description:何为生产者与消费者
 * @author: 
 * @date:2018年5月3日
 */
public class Restraurant {
	Meal m=null;
	Chef chef=new Chef(this);
	WaitPerson wait=new WaitPerson(this);
	ExecutorService service=Executors.newCachedThreadPool();
	public Restraurant() {
		service.execute(chef);
		service.execute(wait);
	}
	public static void main(String[] args) {
		new Restraurant();
	}
}
/**
 * @ClassName:Meal
 * @Description:生产者生成的数据
 * @author: 
 * @date:2018年5月3日
 */
class Meal{
	private final int orderNum;//食物订单编号
	public Meal(int num){
		orderNum=num;
	}
	public String toString(){
		return "Meal"+orderNum;
	}
}
/**
 * @ClassName:Chef
 * @Description:厨师类,及生产者
 * @author: 
 * @date:2018年5月3日
 */
class Chef implements Runnable{
	Restraurant r;
	int count=0;
	public Chef(Restraurant r) {
		this.r=r;
	}
	@Override
	public void run() {
		try{
			while(!Thread.interrupted()){
				synchronized (this) {
					while(r.m!=null){
						System.out.println("厨师等待中");
						wait();//等待服务员取餐
					}
				}
				if(count++==10){
					System.out.println("今日已售完");
					r.service.shutdownNow();
				}
				System.out.println("订单完成,服务员取餐");
				synchronized (r.wait) {
					r.m=new Meal(count);
					r.wait.notifyAll();
					
				}
				TimeUnit.SECONDS.sleep(1);
			}
		}catch (InterruptedException e) {
			System.out.println("生产者线程强制中断");
		}
		
	}
}
/**
 * @ClassName:WaitPerson
 * @Description:服务员类,即消费者
 * @author: 
 * @date:2018年5月3日
 */
class WaitPerson implements Runnable{
	Restraurant r;
	public WaitPerson(Restraurant r) {
		this.r=r;
	}
	@Override
	public void run() {
		try {
			while (!Thread.interrupted()) {
				synchronized (this) {
					while (r.m == null) {
						System.out.println("服务员等待中");
						wait();// 等待厨师生成食物
					}
				}

				System.out.println("服务员以取餐" + r.m);
				synchronized (r.chef) {
					r.m = null;
					r.chef.notifyAll();
				}
			}
		} catch (InterruptedException e) {
			System.out.println("消费者线程强制中断");
		}
		
	}
	
}

猜你喜欢

转载自my.oschina.net/u/3352298/blog/1806314