部分内容来自以下博客:
https://blog.csdn.net/historyasamirror/article/details/6709693
1 锁对象发生了改变
在测试多线程通信的代码时,出现了这个异常。
1.1 代码分析
代码如下:
public class Demo {
public static void main(String[] args) {
DemoThread demoThread = new DemoThread();
Thread thread1 = new Thread(demoThread);
Thread thread2 = new Thread(demoThread);
thread1.start();
thread2.start();
}
}
class DemoThread implements Runnable {
private Integer num = 1;
@Override
public void run() {
while (true) {
synchronized (num) {
num.notify();
if (num <= 10) {
System.out.println(Thread.currentThread().getName() + " >>> " + num++);
try {
num.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
运行结果如下:
Thread-0 >>> 1
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.iyao.ide.engine.task.DemoThread.run(Demo.java:22)
at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at