wait()调用时出现IllegalMonitorStateException [英] IllegalMonitorStateException on wait() call

查看:146
本文介绍了wait()调用时出现IllegalMonitorStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中为我的程序使用多线程。
我已经成功运行了线程但是当我使用 Thread.wait()时,它正在抛出 java.lang.IllegalMonitorStateException
我怎样才能使线程等到通知为止?

I am using multi-threading in java for my program. I have run thread successfully but when I am using Thread.wait(), it is throwing java.lang.IllegalMonitorStateException. How can I make a thread wait until it will be notified?

推荐答案

你需要在一个 synchronized 阻止 Object.wait()工作。

You need to be in a synchronized block in order for Object.wait() to work.

另外,我建议查看并发包而不是旧的学校线程包。它们更安全,更方便与...合作。

Also, I recommend looking at the concurrency packages instead of the old school threading packages. They are safer and way easier to work with.

快乐编码。

编辑

我认为你的意思是 Object.wait(),因为你的例外情况是当你试图获得访问而没有持有对象锁时会发生什么。

I assumed you meant Object.wait() as your exception is what happens when you try to gain access without holding the objects lock.

这篇关于wait()调用时出现IllegalMonitorStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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