gpt4 book ai didi

java - 等待并通知 IllegalMonitorStateException 匿名类

转载 作者:行者123 更新时间:2023-12-01 21:44:26 25 4
gpt4 key购买 nike

根据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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com