本文链接:https://blog.csdn.net/lr222584/article/details/54572676
出现java.lang.IllegalMonitorStateException错误,由以下情况导致:
1>当前线程不含有当前对象的锁资源的时候,调用obj.wait()方法;
2>当前线程不含有当前对象的锁资源的时候,调用obj.notify()方法。
3>当前线程不含有当前对象的锁资源的时候,调用obj.notifyAll()方法。
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public class ThreadTest { class ThreadTest1 extends Thread{ String a; public ThreadTest1(String a){ this.a=a; } public void run(){ try { a.wait(); } catch (InterruptedException e) { } } } public static void main(String[] args){ String a="11"; ThreadTest test = new ThreadTest(); ThreadTest1 test1 = test.new ThreadTest1(a); test1.start(); } }
以上程序运行后会出现错误:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at ThreadTest$ThreadTest1.run(ThreadTest.java:11)
解决办法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public class ThreadTest { class ThreadTest1 extends Thread{ String a; public ThreadTest1(String a){ this.a=a; } public void run(){ try { synchronized (a) {//在执行a.wait()前,先让当前线程获取a的锁 a.wait();
}} catch (InterruptedException e) {}}}public static void main(String[] args){String a="11";ThreadTest test = new ThreadTest();ThreadTest1 test1 = test.new ThreadTest1(a);test1.start();}}
修改后便可以顺利运行
————————————————
版权声明:本文为CSDN博主「lr222584」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lr222584/article/details/54572676
最后
以上就是缥缈大船最近收集整理的关于java.lang.IllegalMonitorStateException错误的解决的全部内容,更多相关java.lang.IllegalMonitorStateException错误内容请搜索靠谱客的其他文章。
发表评论 取消回复