JAVA同步-生产者与消费者实现 一

生产者消费者模型:

实现手段 用wait(),notifALL()实现;

问题描述:在一个餐馆里,有一个厨师(做食物),有一个伙计(端食物/消费);

                 食物为空时:伙计不能再端食物,此时通知厨师要做菜;

                 食物不为空时: 厨师就不再做食物,通知伙计消费食物;

//此处问题抽象:厨师每次只能做一样食物(只有一个盘子),可以做多次;

 

食物类:

class Meal1{
	static int cnt;
	Meal1(int i){cnt=i;}
	@Override
	public String toString() {
		return "第"+cnt+"盘"+"食物";
	}
}

伙计类:

class WaitPerson1 implements Runnable{
private Restaurant1 restaurant1;
	
	WaitPerson1(Restaurant1 restaurant){
	    this.restaurant1=restaurant;
	}
	public void run() {
		try {
			while(!Thread.interrupted())
			{   //餐馆食物为空时:伙计等待
				synchronized(this)
				{   
					while(this.restaurant1.meal1==null){
						this.wait();           
					}
				}
				//食物不为空才能执行以下语句;
				System.out.println("消费掉:"+this.restaurant1.meal1+"!");
			
				synchronized(this.restaurant1.chef1){
					this.restaurant1.meal1=null;       //消费食物
					this.restaurant1.chef1.notifyAll();	//通知厨师工作
				}
			}
		} catch (InterruptedException e) {
			System.out.println("伙计打断操作!");	
			e.printStackTrace();
		}
	}
	
}


厨师类:

class Chef1 implements Runnable{

    private Restaurant1 restaurant1;
	
    Chef1(Restaurant1 restaurant){
	    this.restaurant1=restaurant;
	}
	public void run() {
		try {
			while(!Thread.interrupted())
			{   //餐馆食物为不为空时:厨师等待
				synchronized(this)
				{   
					while(this.restaurant1.meal1!=null){
						this.wait();           
					}
				}
				//食物为空才能执行以下语句;
				
				if(++Meal1.cnt==11){    //一共上10盘食物  ,超过后打断线程
					this.restaurant1.exec.shutdownNow();
				}
				
				synchronized(this.restaurant1.waitPerson1){
					this.restaurant1.meal1=new Meal1(Meal1.cnt);//生成新食物并编号
					this.restaurant1.waitPerson1.notifyAll();//通知伙计工作
				}
			}
		} catch (InterruptedException e) {
			System.out.println("厨师打断操作!");
			e.printStackTrace();
		}
		
	}
	
}

餐馆类:

class Restaurant1 {
	Meal1 meal1;
	//此处必须传入this指针不可以新生成;因为在逻辑下只有一个餐馆;
	Chef1 chef1 = new Chef1(this);
	WaitPerson1 waitPerson1 = new WaitPerson1(this);
	ExecutorService exec = Executors.newCachedThreadPool();

	public Restaurant1() {
		exec.execute(chef1);
		exec.execute(waitPerson1);
	}
}

测试:

 public class TestRestaurant {
		public static void main(String[] args) {
			new Restaurant1();
		}
}

结果:


















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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值