小编Evg*_*nii的帖子

为什么在调用对象的 wait 方法之前,线程应该拥有完全相同的对象的监视器?

我正在学习并发任务之间的合作,我已经得到了这个问题和可能的答案。我想确保我理解正确。

\n\n

因此,要调用a.wait()它,首先需要在对象上同步a,或者更准确地说,线程必须成为a监视器的所有者。据我了解,a.wait()应该在同步上下文中调用(与a.notify()/一起a.notifyAll())的唯一原因是为了避免竞争条件/丢失唤醒问题。但理论上,可以通过在其他对象上同步来避免竞争条件调用,如下所示a.wait()a.notify()/a.notifyAll()

\n\n
Thread #1: \nsynchronized(b) { \n    \xe2\x80\xa6\n    a.wait(); // here a thread owns only one monitor: the monitor of the object stored in the variable b, where a != b\n    \xe2\x80\xa6\n}\n\nThread #2: \nsynchronized(b) {\n    \xe2\x80\xa6\n    a.notify(); // the same here\n    \xe2\x80\xa6\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

The expected behavior is: the thread #1 acquires the monitor of b, enters the critical section, invokes …

java concurrency multithreading wait thread-synchronization

6
推荐指数
0
解决办法
721
查看次数