Re: notify() and wait()
On 01/09/2010 04:00 PM, Jack wrote:
If thread1 calls myObject.notify() first, then thread2 calls
myObject.wait(). The wait() still blocks thread2, right?
Right.
In general, it is difficult to control the timing of notify() and wait
() call. How to prevent this situation.
Well, notify/wait has specific semantics. In pthreads, the equivalent
feature is the condition variable: you want to wait (hence the method
name) until a condition becomes true; another thread will notify you
that the condition is true.
If you have a notify which is only being called once, you're probably
using the wrong thing. A classic example of wait/notify is if you're
trying to manage a buffer where different threads consume and produce:
you wait when the buffer has too much or too little (two separate
variables), and you notify when you remove or add, respectively.
When I call notify() and wait(), must I put them in a synchronized
block?
Yes. Actually, you should also put your condition check inside the
synchronized block as well. In a while loop (to avoid spurious wakeup).
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth