aspose file tools*
The moose likes Threads and Synchronization and the fly likes Wait and notify sample does not work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Wait and notify sample does not work" Watch "Wait and notify sample does not work" New topic
Author

Wait and notify sample does not work

Celina Paul
Greenhorn

Joined: Nov 01, 2003
Posts: 16
The following wait and notify sample does not work.
Please can somebody let me know what is wrong ?




The output that I see is -
"Notified all the waiting threads"

and then it hangs for ever
[ August 03, 2004: Message edited by: Celina Paul ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

This program assumes that waitFor(0) will be called before notifyTo(0), but there's nothing at all that guarantees this will be the case. As written, the two methods could be called in either order, because there's no guarantee which of the two threads will start running first.

If notifyTo() is called first, then the program will hang, as the waitFor() will never return.


[Jess in Action][AskingGoodQuestions]
Celina Paul
Greenhorn

Joined: Nov 01, 2003
Posts: 16
Hi Ernest,

Thanks for the reply.

After reading your comment, I changed the code, so that the Thread t2
sleeps for 10 seconds before calling notify().



This should take care that wait() gets called since the other thread is not sleeping. I still see the same result.

I am expecting to see after the wait is called -
here after being notified

Let me know what is going on here...
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

OK, well, now that you mention it, there is another problem: each Thread has its own TestWaitNotify object, and each TestWaitNotify object has its own array of five Objects -- so that the Object that wait() is called on is never notified; it's another object altogether that is notified, but nothing is waiting.

To fix just use one single TestWaitNotify object to pass to both Thread constructors.
[ August 03, 2004: Message edited by: Ernest Friedman-Hill ]
Celina Paul
Greenhorn

Joined: Nov 01, 2003
Posts: 16
Great ! It works !

Thanks Ernest,
It also cleared few things on the way...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Wait and notify sample does not work