wait() 调用上的 IllegalMonitorStateException [英] IllegalMonitorStateException on wait() call
问题描述
我在 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屋!