Thread-0: started false: started Thread-0: is running Exception in thread "Thread-0" java.lang.IllegalMonitorStateException at java.base/java.lang.Object.wait(Native Method) at java.base/java.lang.Object.wait(Object.java:326) at ThreadInterrupt$1.run(ThreadInterrupt.java:11) at java.base/java.lang.Thread.run(Thread.java:835) main: stopped
时间: 2024-03-20 14:41:24 浏览: 100
这个错误是因为在线程中调用了wait()方法,但是没有获取到对象锁。wait()方法只能在synchronized块中使用,否则就会抛出IllegalMonitorStateException异常。
你可以将wait()方法调用放到synchronized块中,或者使用Lock对象来代替synchronized块。例如:
```
public void run() {
System.out.println(Thread.currentThread().getName() + ": started");
System.out.println(Thread.currentThread().isInterrupted() + ": started");
synchronized (this) {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + ": is running");
try {
wait();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + ": interrupted when sleep");
System.out.println(Thread.currentThread().isInterrupted() + ": interrupted getState()");
Thread.currentThread().interrupt();
System.out.println(Thread.currentThread().isInterrupted() + ": interrupted getState()");
}
}
}
System.out.println(Thread.currentThread().getName() + ": exiting");
}
```
这样修改后,就不会再出现IllegalMonitorStateException异常了。
阅读全文