Re: notify() and wait()
I have two threads: thread1 and thread2 and use myObject for
Object myObject = new Object();
If thread1 calls myObject.notify() first, then thread2 calls
myObject.wait(). The wait() still blocks thread2, right?
In general, it is difficult to control the timing of notify() and wait
() call. How to prevent this situation.
Even ignoring the possibility of spurious wake-ups in Java, the usual
approach would be to have some specific state that needs to be satisfied
for the waiting thread to continue. Then you would check that state in
the synchronized block of code in the waiting thread, and set the state
in the synchronized block of code in the notifying thread.
public class TestNotifyWait
private static boolean _fDone = false;
private static final Object _objLock = new Object();
* @param args
public static void main(String args)
public void run()
_fDone = true;
System.out.println("waiting for thread");
catch (InterruptedException e)
// TODO Auto-generated catch block
Note that this approach also deals with the spurious wake-up issue, by
making sure that even if the wait() method returns, you have _really_
been woken up due to the state change you were expecting, rather than
When I call notify() and wait(), must I put them in a synchronized
As the docs clearly point out, yes. You must own the object's monitor
to call either notify() or wait().