我是在 Java 中使用 wait() 和 notify() 的新手,我收到了 IllegalMonitorStateException。
主要代码
public class ThreadTest {
private static Integer state = 0;
public static void main(String[] args) {
synchronized(state) {
System.out.println("Starting thread");
Thread t = new Thread(new AnotherTest());
t.start();
synchronized(state) {
state = 0;
while(state == 0) {
try {
state.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("State is: " + state);
}
}
}
public static class AnotherTest implements Runnable {
@Override
public void run() {
synchronized(state) {
state = 1;
state.notify();
}
}
}
}
我得到一个 IllegalMonitorStateException 什么 state.notify() 被调用。有任何想法吗?
编辑:根据下面的答案,这里是有效的代码。作为旁注,我首先尝试使用与使用整数有相同问题的枚举。
public class ThreadTest {
private static int state = 0;
private static Object monitor = new Object();
public static void main(String[] args) {
synchronized(monitor) {
System.out.println("Starting thread");
Thread t = new Thread(new AnotherTest());
t.start();
state = 0;
while(state == 0) {
try {
for(int i = 0; i < 5; i++) {
System.out.println("Waiting " + (5 - i) + " Seconds");
Thread.sleep(1000);
}
monitor.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("State is: " + state);
}
}
public static class AnotherTest implements Runnable {
@Override
public void run() {
synchronized(monitor) {
state = 1;
monitor.notify();
}
}
}
}