多个线程可以同时等待一个对象吗?
如果 wait 只能从同步上下文中调用,并且只能在持有对象锁的情况下对对象调用 wait,那么多个线程如何等待同一个对象呢?此外,由于notify也必须从同步上下文中调用,那么notify如何发生呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
wait 方法释放它正在等待的对象上的锁。一旦释放,另一个对象就可以获取锁并等待或通知。而且,这一切都在javadoc 中。
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.
不是对您问题的直接答案,但您可以使用 CountDownLatch 类在 Java 5 上引入的并发包中。您可以在要等待的类和方法上初始化
CountDownLatch
等待它应该执行方法await(),并调用方法countDown()来释放锁存器。在我看来,它比使用 wait() 更干净、更清晰。 《Effective Java》一书有一个关于此类的非常有趣的主题。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.