Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding working of wait() and notifyAll() in Threads

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all

Please have a look at the code below:



According to my understanding, the execution of the code is as follows:

1> A separate stack is created for main() thread and it is loaded in to the JVM.

2> An instance of Calculator class is created.

3> This instance(calculator) is passed on to the overloaded constructor of the Reader class which initializes variable c and start() is called on that instance.

4> The overridden run() method runs. It acquires a lock on the newly created Thread instance (c) using synchronized(c) and prints "Waiting for calculation to complete..."

5> The currently executing thread (c) is placed on hold using c.wait();

6> Similarly, two more times steps 3,4,5 are repeated and in Toto 3 new call stacks have been created and the 3 threads have been placed on them respectively.

6> Next, the calculator thread is started and the calculation is completed in the run() method of Calculator class.

7> Finally, after calculation has been completed, the calculator thread notifies the threads in runnable condition (all three threads created above) that not to wait anymore and execute the following:

System.out.println("Total is : " + c.total);

and we get the output:

Waiting for calculation to complete...
Waiting for calculation to complete...
Waiting for calculation to complete...
Total is : 4950
Total is : 4950
Total is : 4950

Please correct me if I am wrong. Kindly suggest if I missed out on something or made a mistake as I have studied Threads for the first time.

Regards
Mansukhdeep Singh
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is a good description of what happens in this program, yes.

We have a forum for discussing Threads, and I am going to move this there.
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Friedman-Hill wrote:That is a good description of what happens in this program, yes.

We have a forum for discussing Threads, and I am going to move this there.


Thank you Ernest.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic