简体   繁体   English

在synchronized语句中的wait(),notify()和notifyAll()

[英]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.

相关问题 为什么等待/通知/通知所有方法在 java 中不同步? - why wait/notify/notifyAll methods are not synchronized in java ? 为什么不调用wait(),notify()或notifyAll()而没有同步块而不是编译器错误? - Why isn't calling wait(), notify() or notifyAll() without a synchronized block not a compiler error? Java 中的线程 | 等待(),通知()和通知所有() - Threads in Java | wait(), notify() and notifyAll() 同步,wait/notifyAll 必须在同一个对象上,但为什么呢? - synchronized, wait/notifyAll has to be on the same object, but why? Java线程同步死锁wait(); notifyAll(); - Java Thread synchronized Deadlock wait(); notifyAll(); 使用tryLock()以及wait()和notify()/ notifyAll() - using tryLock() together with wait() and notify()/notifyAll() 为什么等待,通知和notifyAll方法都在Object Class中? - Why wait ,notify and notifyAll Methods are in Object Class? 用wait,notify和notifyAll替换Await,Signal,SignalAll - Replace Await, Signal, SignalAll with wait,notify and notifyAll 是否需要在同步块内使用线程wait()和notify()? - Is it required to use thread wait() and notify() inside a synchronized block? 尽管同步,wait()和notify()是否不可靠? - Are wait() and notify() unreliable despite of synchronized?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM