| Author |
notifyAll() not working
|
Vidya Venkatesh
Greenhorn
Joined: Mar 06, 2003
Posts: 12
|
|
hello friends In this program I'm not able to bring the thread t1 out of the waiting state. Isn't notifyAll() supposed to wake up all waiting threads. Am I doing anything wrong ? class TestThread extends Thread { public void startMe() { synchronized(this) { notifyAll(); System.out.println("Not"); } } public void run() { try { synchronized(this) { wait(); System.out.println("Notified"); } } catch(InterruptedException e) {} } public static void main(String[] args) { TestThread t1 = new TestThread(); t1.start(); t1.startMe(); } } Thanks Vidya [ April 23, 2003: Message edited by: Vidya Venkatesh ]
|
 |
Rory French
Ranch Hand
Joined: Apr 03, 2003
Posts: 97
|
|
The problem arises because your t1.startMe() method is being invoked before your t1 thread runs. Consequently, the call to notifyAll() is invoked before the call to wait(). If this happens (i.e. notify is called before wait), the thread could wait forever unless another notify call is made on the same object. It is good practice therefore to put in a test condition before calling wait to avoid the problem. I have ammended your code to provide an example of such a test condition. Alternatively, if you want your program to run as is AND output "Notified", you could invoke the Thread.sleep() method on your main thread (i.e. the one that calls t1.startMe()) with a time parameter, directly after the call to t1.start(). This would give thread t1 a chance to run and call wait() before the call to notifyAll(). Hope this helps. [ April 23, 2003: Message edited by: Rory French ] [ April 23, 2003: Message edited by: Rory French ] [ April 23, 2003: Message edited by: Rory French ]
|
 |
Vidya Venkatesh
Greenhorn
Joined: Mar 06, 2003
Posts: 12
|
|
Thanks so much. Now it is clear to me Vidya
|
 |
John Zoetebier
Ranch Hand
Joined: Mar 28, 2003
Posts: 76
|
|
The solution offered by Rory prevents an eternal wait, but does not show that notifyAll() wakes all waiting threads. If you just run the program a number of times you will see that wait() is never called. It is not difficult to see why. The main thread is already running. Consequently method startMe() will already have run by the time the second thread is executing. To show that notifyAll() really wakes up the second thread call join on the second thread with a timeout of about 1 second, depending on the speed of your processor. The following is a modifed version what shows this point:
|
 |
 |
|
|
subject: notifyAll() not working
|
|
|