当我以静态方式同步块调用 wait() 时,为什么 Java 会抛出 java.lang.IllegalMonitorStateException?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21149139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why Java throw java.lang.IllegalMonitorStateException when I invoke wait() in static way synchronized block?
提问by koralgooll
I do not understand why Java throw exception from subject in this code. Could somebody explain me it?
我不明白为什么 Java 在这段代码中从主题抛出异常。有人可以给我解释一下吗?
class Wait implements Runnable
{
public void run() {
synchronized (Object.class) {
try {
while(true) {
System.out.println("Before wait()");
wait();
System.out.println("After wait()");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ObjectMethodInConcurency
{
public static void main(String[] args) {
Wait w = new Wait();
(new Thread(w)).start();
}
}
采纳答案by Nu2Overflow
Use synchronized (this) {instead of synchronized (Object.class)in your class
在您的类中使用synchronized (this) {而不是 synchronized (Object.class)
EDIT
编辑
Reasoning behind the IllegalMonitorException in above code
上述代码中 IllegalMonitorException 背后的推理
In Java using synchronized keyword is a way to create and obtain a monitor object which will be used as lock to execute corresponding code block.
在 Java 中使用 synchronized 关键字是一种创建和获取监视器对象的方法,该对象将用作锁来执行相应的代码块。
In the above code that monitor is "Object.class".
在上面的代码中,监视器是“Object.class”。
And wait() method tells the current thread to wait until it is notifyed and you have to invoke wait() on the monitor object which owns the lock.
并且 wait() 方法告诉当前线程等待直到它被通知并且您必须在拥有锁的监视器对象上调用 wait() 。
So the way to invoke wait() method is like below otherwise you will get IllegalMonitorException.
所以调用wait()方法的方法如下,否则你会得到IllegalMonitorException。
synchronized(monitor){
monitor.wait();
}
So for your example you can either use "Object.class.wait()"
or change the monitor to this
since you are calling wait()
method on the current instance
因此,对于您的示例,您可以使用"Object.class.wait()"
或更改监视器,this
因为您正在wait()
当前实例上调用方法