以下是一个生产者与消费者的DEMO,但是运行过程中出现死锁,请问原因是什么?
Production类:
@Data
public class Production {
private int id;
private boolean flag;
public Production() {
id = 0;
flag = false;
}
}
生产者类:
public class Productor {
private Production production;
public Productor(Production production) {
this.production = production;
}
public synchronized void product() {
if (!production.isFlag()) {
production.setId(production.getId() + 1);
System.out.println(Thread.currentThread().getName() + "product第: " + production.getId());
production.setFlag(!production.isFlag());
notifyAll();
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者类:
public class Consumer {
private Production production;
public Consumer(Production production) {
this.production = production;
}
public synchronized void consume() {
if (production.isFlag()) {
System.out.println(Thread.currentThread().getName() + "consume第: " + production.getId());
production.setFlag(!production.isFlag());
notifyAll();
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
跑起来:
public class ThreadTest {
public static void main(String[] args) {
Production production = new Production();
Productor productor = new Productor(production);
Consumer consumer = new Consumer(production);
new Thread(() -> {
for (int i = 0; i < 100; i ++ ) productor.product();
}).start();
new Thread(() -> {
for (int i = 0; i < 100; i ++ ) consumer.consume();
}).start();
}
结果:
Thread-0product第: 1
Thread-1consume第: 1
...没有下文了