File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Threads: wait+notify

 
Vega Zimur
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


If I just create this object with an initial value of 1000 in the main function and start it, it prints "Timer ticked" every second.

But it doesn't work to wake waiting threads with this code:
 
Garik Ustinov
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your synchronization is definitely broken. Before calling wait() and notify() on some object you must obtain the lock for this object. In Timer you're synchronizing on this and then calling this.notifyAll() (everything's fine), but in Timertest you're synchronizing on this and calling timer.wait() - and I guess you see an exception.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not a "beginning" topic. Moving to our threads forum.
 
Vega Zimur
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, it says "interrupted" every time the for loop executes again.
but how do I get the lock of the timer object? -> what do I have to add to the code?

If I change the method of TestTimer like this, I don't get an error, but the Thread waits forever:
 
Garik Ustinov
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't get an error, but the Thread waits forever.


Yup, it does indeed. The problem is that run() method in Timer is synchronized, which means it holds the lock all the time and never releases it, so TimerTest never has a chance to get it, so it just waits. Instead of synchronizing the whole method you have to narrow the synchronized block, so the Timer thread would release the lock from time to time.
What you need is something like this (and remove synchronized from method declaration)
 
Vega Zimur
Greenhorn
Posts: 9
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, if I do it like this, it works

 
Garik Ustinov
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Well done about putting sleep outside synchronized - I've put it wrong.
PS. there's no need to declare run() as synchronized in TestTimer. You don't really want to use more locks than you need, otherwise one day you may end up in a deadlock
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic