Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with wait() / notify()

 
James Hodgkiss
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply. I decided to go for a less elegant polling solution in the end. Cheers, James.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic