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;
}
}
【java基础】多线程--生产者消费者--复习
最新推荐文章于 2021-02-16 02:19:10 发布