If wait can only be called from a synchronized context, and you can only call wait on an object while holding its lock, then how can multiple threads wait on the same object? Furthermore, since notify must also be called from a synchronized context, how can the notify occur?
The wait method releases the lock on the object on which it is waiting. Once released, another object can then acquire the lock and also wait or notify. And, this is all right there in the javadoc.
Not a direct answer to your question, but instead of using the wait method, you could use the CountDownLatch class in the concurrent package introduce on Java 5. You can initialize the CountDownLatch
on the class you are going to wait for, and methods waiting for it should execute the method await(), and to release the latch you invoke the method countDown(). It is more clean and clear than using wait() in my opinion. The Effective Java book has a really interesting topic about this class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With