[英]Wait And Notify IllegalMonitorStateException Anonymous Class
根据如何在Java中使用等待和通知? 我必须在同一对象上进行同步以调用notify。
我已经在同一个haveCoffee对象上进行了同步。 为什么在调用notify方法时出现IllegalMonitorStateException?
I am Sleeping
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.example.concurrent.basic.WaitAndNotify$2.run(WaitAndNotify.java:42)
在以下代码中:
public class WaitAndNotify {
public static void main(String[] args) {
Thread haveCoffee = new Thread() {
public void run() {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("I am awake and ready to have coffee");
}
}
};
Thread me = new Thread() {
public void run() {
synchronized (haveCoffee) {
try {
System.out.print("I am Sleeping");
Thread.sleep(4000);
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
haveCoffee.start();
me.start();
}
}
在第一个线程上,在有对象的监视器(对象是此haveCoffee
)上调用wait。
但是,在第二个线程上,您在监视haveCoffee
同时对me
调用notify()
。
这应该工作:
public class WaitAndNotify {
public static void main(String[] args) {
final Thread haveCoffee = new Thread() {
public void run() {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("I am awake and ready to have coffee");
}
}
};
Thread me = new Thread() {
public void run() {
synchronized (haveCoffee) {
try {
System.out.print("I am Sleeping");
Thread.sleep(4000);
haveCoffee.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
haveCoffee.start();
me.start();
}
}
从oracle文档页面 ,
public class IllegalMonitorStateException
extends RuntimeException
抛出该异常指示线程试图在对象的监视器上等待,或者通知其他线程在对象监视器上等待而没有拥有指定的监视器。
每当您遇到此异常时,只需遍历代码并检查wait()
和notify()
调用以及object on which these calls have been invoked
的object on which these calls have been invoked
。 您可以轻松找出问题所在。
编辑:
一旦在该对象上获得监视,就必须在该对象上调用wait()
或notify()
调用。
你应该打电话
haveCoffee.notify()
而不只是
通知()。
如果仅调用notify()
它将在this
对象上调用notify()
方法,这是me
在haveCoffee
线程上同步的第二个线程,这就是您看到异常的原因。
因此,在线程2的代码me
应该是这样的:
synchronized (haveCoffee) {
try {
System.out.print("I am Sleeping");
Thread.sleep(4000);
haveCoffee.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.