边生产边消费实现

如何实现边生产边消费;

首先定义一个生产和消费的类,创建一个生产函数,创建一个消费函数。 定义一个容器用于装载生产出来的产品,这里我用一个数组当做一个容器。定义一个变量用于标识产品的个数。 使用synchronized同步,使生产与消费的方法同时执行。定一个消费线程B类,用于消费。定义一个生产线程A类,用于生产。用一个while循环判断产品的个数是否与数组的长度相等,如果相等,使A线程进入等待状态然后唤醒B线程。消费方法也用一个while循环判断产品个数是否等于0,如果等于0,那么B线程进入等待状态,然后唤醒A线程继续生产。如此就可以实现边生产边消费了。

public class ProdutionAndConsume {


public static void main(String[] args) {
// TODO Auto-generated method stub
PC pc = new PC();
AB a = new AB(pc);
BC b = new BC(pc);
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
t1.start();
t2.start();
}


}
class PC {
int[] aa = new int[7]; //定义一个容器装生产的产品
int cut = 0; //生产的总个数
public synchronized void push(int a){
while(cut==aa.length-1){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
aa[cut]  = a;
System.out.println(Thread.currentThread().getName()+"生产了"+(cut+1)+"个产品");
cut++;

}
public synchronized int  popup(){
int b = 0;
while(cut==0){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notify();
b  = aa[cut-1];
System.out.println(Thread.currentThread().getName()+"消费了"+cut+"个产品");
cut--;

return b;
}
}
class AB implements Runnable{//生产线程
PC pc = null;
public AB(PC pc){
this.pc = pc;
}
public void run(){
for (int i = 0; i < 22; i++) {

pc.push(1);
}

}
}


class BC implements Runnable{ //消费线程
PC pc = null;
public BC(PC pc){
this.pc = pc;
}
public void run(){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 22; i++) {
pc.popup();

}
}
}


猜你喜欢

转载自blog.csdn.net/qq_40207976/article/details/79523703