下面是一个线程安全的消费者、生产者实现,i 为共享变量,i 为 1 时消费,i 为 0 时生产;
但写完我有两个问题:
1. 在本地运行时,为什么使用 this.notify() 会出现运行一段时间就卡住了,像死锁一样。而用this.notifyAll() 就没有问题?
2. 为什么主线程没有使用join、sleep的方法,在启动完其他线程后变为阻塞状态,而不是结束?
// 多线程环境下的生产者和消费者
public class ThreadTest {
volatile Integer i = 0;
private synchronized void add() {
while (i > 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("add: " + ++i);
// TODO 问题1:这里用 this.notify() 运行一会就卡住,像死锁一样,不知道为什么?
this.notifyAll();
}
private synchronized void reduce() {
while (i < 1) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("red: " + --i);
// TODO 问题1:这里用 this.notify() 运行一会就卡住,像死锁一样,不知道为什么?
this.notifyAll();
}
public static void main(String[] args) throws InterruptedException {
ThreadTest test = new ThreadTest();
Runnable reduceR = () -> {
while (true) {
test.reduce();
}
};
Thread reduceT1 = new Thread(reduceR);
Thread reduceT2 = new Thread(reduceR);
Thread reduceT3 = new Thread(reduceR);
Runnable addR = () -> {
while (true) {
test.add();
}
};
Thread addT1 = new Thread(addR);
reduceT1.start();
reduceT2.start();
reduceT3.start();
addT1.start();
// TODO 问题2:主线程没有用sleep、join等方法, 应该到这就结束了,但实际中没有,而是阻塞状态,为什么?
}
}