日期:2014-05-20 浏览次数:20813 次
public class RunCandP {
public static void main(String[] args) {
pot P1 = new pot();
consumer C1 = new consumer(P1);
cooker Co1 = new cooker(P1);
new Thread(Co1).start();
new Thread(C1).start();
}
}
public class consumer implements Runnable {
pot P = null;
public consumer(pot P){
this.P = P;
}
public void run(){
for (int f=0;f<20;f++){
P.get();
System.out.println("吃了面包"+bread.all+" "+P.index);
}
}
}
public class cooker implements Runnable {
pot P =null;
public cooker(pot P){
this.P=P;
}
public void run(){
for(int f=0;f<20;f++){
P.add(new bread());
System.out.println("生产了"+bread.all+" "+P.index);
}
}
}
public class pot {
bread[] p=new bread[6];
int index=0;
public synchronized void add(bread a){
try{
while (index == p.length) {
System.out.println("停止生产,等待中...");
this.wait();
}}catch(InterruptedException e) {
System.out.println("添加出错。");
}
this.notify();
p[index]=a;
index++;
}
public synchronized bread get(){
try {
while (index == 0) {
System.out.println("没有得吃了,等待生产...");
this.wait();
}}catch(InterruptedException e){
System.out.println("消费出错。");
}
this.notify();
bread a = this.p[index];
this.p[index]=null;
index--;
return a;
}
}
public class bread {
static int all=0;
bread(){
all++;
}
public String toString() {
return "bread:"+"第"+all+"个";
}
}