Two Laptop Bag*
The moose likes Threads and Synchronization and the fly likes Doubt regarding working of wait() and notifyAll() in Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Doubt regarding working of wait() and notifyAll() in Threads" Watch "Doubt regarding working of wait() and notifyAll() in Threads" New topic
Author

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

Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

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

~ Mansukh
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
Mansukhdeep Thind
Ranch Hand

Joined: Jul 27, 2010
Posts: 1157

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.
 
 
subject: Doubt regarding working of wait() and notifyAll() in Threads