代码
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/