这个多线程生产消费包子,我的生产完5个为什么还停留在p1线程,没搞懂,不是wait了么
我的解答思路和尝试过的方法
public class Demo {
public static void main(String[] args) {
ProductThread p1 = new ProductThread(0);
ProductThread c1 = new ProductThread(1);
ProductThread c2 = new ProductThread(1);
ProductThread c3 = new ProductThread(1);
p1.start();
c1.start();
c2.start();
c3.start();
}
}
class ProductThread extends Thread{
public static int num = 0;
public static boolean flag = true;
private int post;
public ProductThread(int post) {
this.post = post;
}
@Override
public void run() {
if(post==0){
this.product();
}else {
this.consume();
}
}
private synchronized void consume() {
while(true){
if(flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"吃了一个包子,还剩"+(--num)+"个包子");
if(num==0){
flag=true;
notifyAll();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void product(){
while(true){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("做了一个包子,还剩"+(++num)+"个包子");
if(num==5){
flag=false;
notifyAll();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}