This is my code and output are different anytime that I run the code. Sometimes all three readers will be notified and output is:
Waiting for calculation...
Waiting for calculation...
Waiting for calculation...
Finished
Total is: 4950Thread-1
Total is: 4950Thread-2
Total is: 4950Thread-0
and sometimes just two or one reader will be notified. what is the problem?
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();
}
}
}
As per the meta post, this question is claimed to be a duplicate, but both "duplicates" that have been dupe-hammered simply do not apply. How to use wait and notify in Java? reminds users that if you truly want to wait on the same object, you have to synchronize on that object. But this solution is already doing this. Java: notify() vs. notifyAll() all over again reminds users the difference between notify
and notifyAll
which is even further from the problem.