【发布时间】:2017-07-20 22:56:00
【问题描述】:
这是我的代码,每次运行代码时输出都会有所不同。有时会通知所有三个读者并输出:
等待计算...
等待计算...
等待计算...
完成
总数为:4950Thread-1
总数为:4950Thread-2
总数为:4950Thread-0
有时只会通知两个或一个读者。 有什么问题?
class Reader extends Thread {
Calculator c;
public Reader(Calculator calc) {
c = calc;
}
public void run() {
synchronized (c) {
try {
System.out.println("Waiting for calculation...");
c.wait();
} catch (InterruptedException e) {
}
System.out.println("Total is: " + c.total +Thread.currentThread().getName());
}
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
new Reader(calculator).start();
new Reader(calculator).start();
new Reader(calculator).start();
new Thread(calculator).start();
}
}
class Calculator implements Runnable {
int total;
public void run() {
synchronized (this) {
for (int i = 0; i < 100; i++) {
total += i;
}
System.out.println("Finished");
notifyAll();
}
}
}
根据元帖子,这个问题声称是重复的,但是被欺骗的两个“重复”根本不适用。 How to use wait and notify in Java? 提醒用户,如果你真的想在同一个对象上等待,你必须在那个对象上进行同步。但是这个解决方案已经在这样做了。 Java: notify() vs. notifyAll() all over again 提醒用户notify 和notifyAll 之间的区别,这甚至进一步问题。
【问题讨论】:
-
在 MacOS/JDK 1.8 上为我工作!
-
Calculator 可以在 Reader 开始等待之前通知。
-
BTW 扩展 Thread 并不可取。
-
@JarrodRoberson 这不是一个重复的问题。该问题的答案已在他的问题中使用。相反,他正在这样做,但没有考虑线程调度程序的微妙复杂性。
-
打开了一个元问题来解决这个问题 - meta.stackoverflow.com/questions/352598/…
标签: java multithreading java-threads