【发布时间】:2016-03-20 08:28:40
【问题描述】:
根据How to use wait and notify in 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.notify()而不是notify()
标签: java multithreading