aspose file tools*
The moose likes Threads and Synchronization and the fly likes Problem with wait() / notify() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Problem with wait() / notify()" Watch "Problem with wait() / notify()" New topic
Author

Problem with wait() / notify()

James Hodgkiss
Ranch Hand

Joined: Jan 22, 2004
Posts: 401
I'm having a problem with my wait / notify code. I understand pretty much how it all works, but the problem is that notify() is being called before wait() and I'm not sure the best way to fix it.

Rather, than post my entire code, I've created this little application which demonstrates the problem.




The associated output is:
running...
wait...
Do something...
doing it...
...done it
notify...
Do something again...
doing it...
...done it
notify...
wait...


I can see why the problem happens, but is there an elegant way to solve it?

Cheers,
James

PS - Why I'm here, can anyone suggest a more elegant solution than "Thread.sleep(1000);" ?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4245
    
    7

Don't you need two loops in two separate threads? At the moment, other than the first call to doSomethingAndRepeat in the main method, you've got the calls to wait and notify in the same thread. Which means the thread is waiting for itself.

This probably isn't what you wanted, but here's a similar example where two threads take it in turns.


James Hodgkiss
Ranch Hand

Joined: Jan 22, 2004
Posts: 401
Thanks for the reply. I decided to go for a less elegant polling solution in the end. Cheers, James.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with wait() / notify()
 
Similar Threads
Calling wait()/ notify() in run()
Why Thread isn't being notified in this case
After notify()
notify()
Synchronizing between two threads, one implements Runnable the other extends Thread