【发布时间】:2023-03-05 05:44:01
【问题描述】:
以下代码出现此错误
First thread about to sleep
thread 1 run
Boolean assignment done.
Woke up and about to invoke wait()
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at IncorrectSynchronization$1.run(HelloWorld.java:23)
at java.lang.Thread.run(Thread.java:748)
当线程 t1 处于休眠状态时,我从另一个线程将锁修改为 false。 然后它抛出这个 IllegalMonitorStateException。还是同一个对象,为什么修改值会导致IllegalMonitorStateException?
当我从同步块内的另一个线程将锁修改为 false 时,我不再收到该错误。谁能解释一下幕后发生的事情的原因?
public class HelloWorld{
public static void main( String args[] ) throws InterruptedException {
SampleTest.runExample();
}
}
class SampleTest{
Boolean flag = new Boolean(true);
public void example() throws InterruptedException {
Thread t0 = new Thread(new Runnable() {
public void run() {
synchronized (flag) {
try {
while (flag) {
System.out.println("First thread about to sleep");
Thread.sleep(2000);
System.out.println("Woke up and about to invoke wait()");
flag.wait();
System.out.println("wait() called");
}
} catch (InterruptedException ie) {
}
}
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
System.out.println("thread 1 run");
flag = false;
}
});
t0.start();
Thread.sleep(200);
t1.start();
t0.join();
t1.join();
}
public static void runExample() throws InterruptedException {
SampleTest test = new SampleTest();
test.example();
}
}
【问题讨论】:
标签: java multithreading locking wait synchronized