关于java中线程的wait()和notify()方法
我知道线程的 wait()
和 notify()
机制,但我无法理解为什么 wait()
和 notify()
方法应该在 synchronized
块中吗?这是强制性的吗?
提前致谢!
I know the mechanism of wait()
and notify()
of thread, but I am unable to understand that why wait()
and notify()
methods should be in synchronized
block? Is this mandatory?
Thanks in Advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用等待/通知时是否强制同步:是
为什么?< /strong>:考虑不需要同步。这意味着线程 A 可以在另一个线程 B 调用 wait()(在同一个对象上)的同一时间调用 notification()。假设线程 B 已经执行了 wait() 方法的一部分,并且进行了上下文切换以服务线程 A。因此 wait 的内部数据结构现在可能处于损坏状态。现在,notify() 方法本质上适用于相同的数据结构,但现在处于无效状态。因此,整个等待/通知可能会被浪费掉。同步保证如果已经调用了其中一个方法,则没有其他方法可以调用等待/通知。
Is synchronized mandatory while invoking wait/notify: Yes
Why?: Consider that synchronizing was not required. That means that a thread A could call notify() exactly at the same time while the other thread B is calling wait()(on the same object). Suppose thread B has executed part of wait() method and is context-switched to serve thread A. So the internal data-structures of wait could be in corrupt state now. Now the notify() method essentially works on the same data-structures, which now is in invalid state. Hence the entire wait/notify could go for a toss. Synchronizing guarantees that no other method could call wait/notify if there is a call to one of them already on.