【java基础】多线程--生产者消费者--复习

package thread;
/**
 *@author kaiscript
 *生产者消费者
 *2016年3月10日下午11:15:17
 */
public class ProductConsumeAgain {

	public static void main(String[] args) {
		WareHouse house = new WareHouse();
		PProducer producer = new PProducer(house);
		CConsumer consumer = new CConsumer(house);
		Thread t1 = new Thread(producer);
		Thread t2 = new Thread(consumer);
		t1.start();
		t2.start();
	}

}

class WareHouse{
	BBread[] breads = new BBread[6];
	int index = 0;
	public synchronized void push(BBread bread) throws InterruptedException{
		while(index == breads.length){//仓库满了,当前生产者线程等待
			this.wait();
		}
		this.notify(); //唤醒其他线程(消费者)
		breads[index] = bread;
		index++;
		
	}
	
	public synchronized BBread pop() throws InterruptedException{
		while(index == 0){//仓库没面包了,当前消费者线程等待
			this.wait();
		}
		this.notify();//唤醒其他线程(生产者)
		index--;
		return breads[index];
	}
	
}
/**
 * 生产者
 */
class PProducer implements Runnable{

	WareHouse house = null;
	
	public PProducer(WareHouse house) {
		this.house = house;
	}


	@Override
	public void run() {
		for(int i = 0 ;i<20;i++){
			BBread bread = new BBread(i);
			try {
				house.push(bread);  //将面包放入仓库
				Thread.sleep(500);  //生产者生产速度快
				System.out.println("生产者生产了面包"+bread.id);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}
/**
 * 消费者 
 */
class CConsumer implements Runnable{
	
	WareHouse house = null;
	
	public CConsumer(WareHouse house) {
		this.house = house;
	}

	@Override
	public void run() {
		for(int i=0;i<20;i++){
			try {
				BBread bread = house.pop();  //从仓库取出面包
				Thread.sleep(1000);
				System.out.println("消费者消费了面包"+bread.id);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
}

class BBread{
	int id;
	public BBread(int id){
		this.id = id;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值