代码
package thread; public class TestChongNeng { public static void main(String[] args) { Thread t1 = new Thread() { public void run() { while (true) { for(int i=1;i<=3;i++) { System.out.printf("波动拳第%d发 %n",i); } try { //synchronized (this) { wait(2000); //} } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println("开始为时2s的充能"); } } }; t1.start(); } }
报错信息
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at thread.TestChongNeng$1.run(TestChongNeng.java:13)
解决方法
在线线程中调用wait方法的时候 要用synchronized锁住对象,确保代码段不会被多个线程调用
参考文章:
https://blog.csdn.net/zhouxiaoyun0228/article/details/7757313/
博客主要围绕 Java 代码报错信息 Exception in thread \Thread-0\ java.lang.IllegalMonitorStateException 展开,指出在线程中调用 wait 方法时,需用 synchronized 锁住对象,确保代码段不被多线程调用,以此解决该报错。
4804

被折叠的 条评论
为什么被折叠?



