why java wants me to put both the wait() and notify() in synchronized methods(or blocks)?
Guess #1:
When a thread invokes wait(), the thread is added to the wait set of the object on which wait() was invoked and the lock of the object is released.
If the thread did not hold the lock of the object when the thread invokes wait(), there would be a race hazard. Another thread could invoke notify() before the first thread is suspended. The notification would have no affect on the thread, effectively getting lost.
----
Guess #2:
Typically, a thread tests a condition before invoking wait.
If the thread did not hold the lock, another thread could change the condition after the first thread tested the condition but before the thread is suspended. The thread would wait forever, even though the condition has changed.
[ December 06, 2003: Message edited by: Marlene Miller ]