同步语句中的 wait()、notify() 和 notifyAll() [英] wait(), notify() and notifyAll() inside synchronized statement

查看:33
本文介绍了同步语句中的 wait()、notify() 和 notifyAll()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在同步语句中尝试调用 notifyAll() 时出现以下错误:在同步上下文之外调用 Object.notify().

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

示例:

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

推荐答案

只能调用 wait()notify()notifyAll() 在被同步的对象上:

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.

如果在synchronized (list)中,你调用了notifyAll(),你实际上是在this上调用了notifyAll() 而不是 list.

If, inside synchronized (list), you call notifyAll(), you are actually calling notifyAll() on this rather than list.

这篇关于同步语句中的 wait()、notify() 和 notifyAll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆