This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes What is this example trying to demonstrate ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "What is this example trying to demonstrate ?" Watch "What is this example trying to demonstrate ?" New topic

What is this example trying to demonstrate ?

Harry Henriques
Ranch Hand

Joined: Jun 17, 2009
Posts: 206

This example is from K + B SCJP Study Guide (Java 6) pp752-753

I don't understand what this example is trying to demonstrate.

I believe that the following is true about the code snippet below:

(1) There is only one Calculator instance, but there are multiple references to the same Calculator instance.
(2) All three run() methods in the three instances of the Reader class synchronize on the same Calculator object.
(3) The main() method in the Reader class creates three Reader threads, starts all three threads, each thread enters the synchonized(c) block and invokes wait() on the same Calculator object.
(4) All three Reader threads enter the wait state virtually immediately after being started.
(5) The Calculator thread only runs once.
(6) All three Reader threads print out the same result, one after the other, after they have been notified to enter Runnable.

My question is this: Do I understand or do I not understand how this code snippet works?

It seems overly complex, and seems to only printout the same result three times in succession.

hph@www:~$ javac
hph@www:~$ java Reader
Total is: 4950
Total is: 4950
Total is: 4950

Ranganathan Kaliyur Mannar

Joined: Oct 16, 2003
Posts: 1101

Your understanding is correct. This just demonstrates the usage of wait() and notifyAll(). But, this is a very poor and confusing example. The example makes the Calculator also a Thread and tries its maximum to complicate and confuse the reader.

I agree. Here's the link:
subject: What is this example trying to demonstrate ?
It's not a secret anymore!