I've defined a Calculator thread which calculates a sum and makes the result available through the getTotal method. The Reader thread keeps a reference to the Calculator and prints the result.
As I wanted the result to the be printed only after the calculation, Reader calls wait() before calling getTotal(). Calculator calls notify() as soon as the result is ready.
In the main method, one Calculator object and three Reader objects are instantiated. The source code is presented below:
Code:public class Calculator extends Thread { private int total; public void run() { for (int i = 0; i < 10; i++) total += i; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this) { notify(); } } public int getTotal() { return total; } }Now the curious stuff: as notify() in called just once, at most one Reader thread would print the result. However, the program ended with the following output:Code:public class Reader extends Thread { Calculator c; public Reader(Calculator c) { this.c = c; } public void run() { synchronized (c) { try { String name = Thread.currentThread().getName(); System.out.println(name + " is waiting..."); c.wait(); System.out.println("(" + Thread.currentThread().getName() + ") total is: " + c.getTotal()); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Calculator c = new Calculator(); new Reader(c).start(); new Reader(c).start(); new Reader(c).start(); c.start(); } }
Thread-1 is waiting...
Thread-2 is waiting...
Thread-3 is waiting...
(Thread-1) total is: 45
(Thread-2) total is: 45
(Thread-3) total is: 45
Even if I leave out the line with the notify() call, the output is the same.
The program just worked as I expected after I modified the way the Calculator thread is started, changing c.start(); to new Thread(c).start();:
Thread-1 is waiting...
Thread-2 is waiting...
Thread-3 is waiting...
(Thread-1) total is: 45
How is it possible ? I thought the synchronization mechanism was independent of the way threads were created. May I consider this a spurious wakeup ?
Thanks in advance


Reply With Quote


Bookmarks