多线程中的生产者和消费者
一、文件结构
二、各个类的作用、和源代码。
.;
public class Bread {
int id;
public Bread(int i){
=i;
}
***@Override
public String toString(){
return "Bread [id=" + id + "]";
}
}
,用于存放面包(Bread对象)
.;
public class Basket{
int index=0;
Bread[] breadBasket=new Bread[12];//定义一个数组存放面包
public synchronized void push(Bread bread){
while(==){//思考为什么不用if
try {
();
} catch(InterruptedException e) {
();
}
}
();//唤醒等待的线程
breadBasket[]=bread;
++;
}
public synchronized Breadpop(){
try {
(1000);
} catch (InterruptedExceptione) {
();
}
while(==0){ //思考为什么不用if
try {
();
} catch(InterruptedException e) {
();
}
}
();//唤醒等待的线程
--;
return breadBasket[];
}
}
.;
public class Producer implements Runnable{
Basket breadBasket=null;
public Producer(Basketbasket){
=basket;
}
***@Override
public void run() {
for(int i=0;i<20;i++){
Bread bread=new Bread(i);
(bread);
("生产者:"+().getName()+"生产"+bread);
}
}
}
Consu
多线程中的生产者和消费者 来自淘豆网www.taodocs.com转载请标明出处.