Re: notify() and wait()
Jack wrote:
I have two threads: thread1 and thread2 and use myObject for
synchronization.
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.
For example:
public class TestNotifyWait
{
private static boolean _fDone = false;
private static final Object _objLock = new Object();
/**
* @param args
*/
public static void main(String[] args)
{
new Thread()
{
public void run()
{
System.out.println("thread started");
synchronized (_objLock)
{
_fDone = true;
_objLock.notify();
}
System.out.println("thread exiting");
}
}.start();
System.out.println("waiting for thread");
synchronized (_objLock)
{
while (!_fDone)
{
try
{
_objLock.wait();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("done");
}
}
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
spuriously.
When I call notify() and wait(), must I put them in a synchronized
block? like:
synchronized(myObject)
{
myObject.notify();
}
As the docs clearly point out, yes. You must own the object's monitor
to call either notify() or wait().
Pete