wait(), notify() and notifyAll() inside synchronized statement

旧城冷巷雨未停 提交于 2019-12-22 09:14:20

问题


I get following error when trying to do invoke notifyAll() inside a synchronized statement: Invoked Object.notify() outside synchronized context.

Example:

final List list = new ArrayList();
synchronized(list) {..... invoked notifyAll() here};

回答1:


You can only call wait(), notify(), and notifyAll() on the object that is being synchronized on:

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.




回答2:


My guess is that you are calling notifyAll() on a different object, one for which you don't hold a lock. In your example, you may call notifyAll() on list, but not on this.




回答3:


A thread must own the lock on the object it's invoking wait, notify, notifyAll on. In the code you posted, the thread owns the lock on 'list' and then it calls notifyAll on 'this' object.



来源:https://stackoverflow.com/questions/7504475/wait-notify-and-notifyall-inside-synchronized-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!