| Author |
How wait() and notify() works?
|
K Raj Kumar
Greenhorn
Joined: Sep 16, 2008
Posts: 17
|
|
Hi Ranchers! This is the code below; I could understand that at label 1, we have used wait(); to prevent ThreadB from finishing or completing the calculation, its stack. And, then we used notify to release the waiting thread and complete the ThreadA. Please explain the inner details esp synchronisation with object b to call wait() on the object and then how notify() acts. Source:SCJP 6 study guide, Kathy sierra and Bert bates , Threads, page 748. Thanks in advance!  [ December 23, 2008: Message edited by: Raj kumar ]
|
With Regards,<br />K.Raj Kumar.
|
 |
Punit Singh
Ranch Hand
Joined: Oct 16, 2008
Posts: 952
|
|
Try to run and understand this code.
|
SCJP 6
|
 |
Punit Singh
Ranch Hand
Joined: Oct 16, 2008
Posts: 952
|
|
I could understand that at label 1, we have used wait(); to prevent ThreadB from finishing or completing the calculation, its stack. And, then we used notify to release the waiting thread and complete the ThreadA. Please explain the inner details esp synchronisation with object b to call wait() on the object and then how notify() acts.
We have used wait(); to prevent main thread from finishing. What is happening here:
b.start();
Main thread called this b.start() to start the threadb.
b.wait(); //1
Main thread called wait() on object b.It will release lock from the b and will wait here until any other thread call notify on the same object. So it will wait here for infinite time. In between threadb's run method is working its task. After completing its for loop it will call notify, that is actually this.notify() and here this object is the same object on which Main thread is waiting.
public void run() { synchronized(this){ for(int i=0; i<100; i++){ total+=i; } notify();//this.notify } }
When threadb will call this.notify() and Main thread will wake up and wait for lock on the same object, notify() does not release lock, but when synchronized(this){} block will complete lock will be released by threadb. Main thread will get the lock on object b again and it will become runnable again, now thread schedular will select it and Main thread will start executing.
|
 |
Brendan Healey
Ranch Hand
Joined: May 12, 2009
Posts: 218
|
|
|
forget it....
|
 |
 |
|
|
subject: How wait() and notify() works?
|
|
|