• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wait and notify sample does not work

 
Celina Paul
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Celina Paul
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great ! It works !

Thanks Ernest,
It also cleared few things on the way...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic