[英]wait(), notify() and notifyAll() inside synchronized statement
I get following error when trying to do invoke notifyAll()
inside a synchronized statement: Invoked Object.notify() outside synchronized context. 尝试在synchronized语句中调用
notifyAll()
时出现以下错误: 在同步上下文外调用Object.notify()。
Example: 例:
final List list = new ArrayList();
synchronized(list) {..... invoked notifyAll() here};
You can only call wait()
, notify()
, and notifyAll()
on the object that is being synchronized on: 您只能对正在同步的对象调用
wait()
, notify()
和notifyAll()
:
synchronized (list) {
//...
list.notifyAll();
}
In other words, the calling thread must own the object's monitor. 换句话说,调用线程必须拥有对象的监视器。
If, inside synchronized (list)
, you call notifyAll()
, you are actually calling notifyAll()
on this
rather than list
. 如果在
synchronized (list)
内部调用notifyAll()
,则实际上是在this
而不是list
上调用notifyAll()
。
My guess is that you are calling notifyAll()
on a different object, one for which you don't hold a lock. 我的猜测是你在另一个对象上调用
notifyAll()
,你没有锁定它。 In your example, you may call notifyAll()
on list
, but not on this
. 在您的示例中,您可以在
list
上调用notifyAll()
,但不能在this
上调用。
A thread must own the lock on the object it's invoking wait, notify, notifyAll on. 一个线程必须拥有对它调用wait,notify,notifyAll的对象的锁。 In the code you posted, the thread owns the lock on 'list' and then it calls notifyAll on 'this' object.
在你发布的代码中,线程拥有'list'上的锁,然后它在'this'对象上调用notifyAll。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.