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

Java Threads: wait+notify

Vega Zimur
Greenhorn

Joined: Jul 14, 2010
Posts: 9


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

Joined: Jun 22, 2009
Posts: 31
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.


SCJP, SCWCD
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39888
    
  28
Not a "beginning" topic. Moving to our threads forum.
Vega Zimur
Greenhorn

Joined: Jul 14, 2010
Posts: 9
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

Joined: Jun 22, 2009
Posts: 31
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

Joined: Jul 14, 2010
Posts: 9
Ok, if I do it like this, it works

Garik Ustinov
Ranch Hand

Joined: Jun 22, 2009
Posts: 31

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
 
wood burning stoves
 
subject: Java Threads: wait+notify