开发者

Can multiple threads wait on one object at once?

开发者 https://www.devze.com 2023-02-25 06:39 出处:网络
If wait can only be called from a synchronized context,开发者_StackOverflow and you can only call wait on an object while holding its lock, then how can multiple threads wait on the same object? Furth

If wait can only be called from a synchronized context,开发者_StackOverflow 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消