根据How to use wait and notify in Java?我必须在同一个对象上同步才能调用通知。
我已在同一个 hasCoffee 对象上进行同步。为什么我在调用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。
但是,在第二个线程上,您在 me
上调用 notify()
,同时拥有 haveCoffee
的监视器。
这应该有效:
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();
}
}
关于java - 等待并通知 IllegalMonitorStateException 匿名类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36111668/