1.报错信息
2020-10-22 17:16:40.044 30626-30672/com.example.uxin.myapplication E/AndroidRuntime: FATAL EXCEPTION: Thread-2
Process: com.example.uxin.myapplication, PID: 30626
java.lang.IllegalMonitorStateException: object not locked by thread before wait()
at java.lang.Object.wait(Native Method)
at threadtest.Thread1.run(Thread1.java:35)
2020-10-22 17:16:40.045 30626-30672/com.example.uxin.myapplication E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
2020-10-22 17:16:40.049 30626-30672/com.example.uxin.myapplication E/AbstractTracker: mTrackerAsyncQueryHandler is null
2.代码
public class Thread1 extends Thread{
private Object object = new Object();
@Override
public void run() {
super.run();
System.out.println("thread1");
System.out.println(this.getState());
System.out.println(this.getThreadGroup().getName());
Log.i("cyp", "run: "+this.getThreadGroup().activeCount());
synchronized (object) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
调用代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread_test);
// 创建线程并启动
thread1 = new Thread1(lockObject);
thread1.start();
Log.i(TAG, "thread1 "+thread1.getState());
}
3。问题原因:在Thead1中直接调用wait方法,是调用的Thread1的的wait方法,而不是synchronized锁的对象即object的wait方法,应该调用object的wait方法,notify/notifyAll方法同样用法
4.代码修改
public class Thread1 extends Thread{
private Object object = new Object();
@Override
public void run() {
super.run();
System.out.println("thread1");
System.out.println(this.getState());
System.out.println(this.getThreadGroup().getName());
Log.i("cyp", "run: "+this.getThreadGroup().activeCount());
synchronized (object) {
try {
// 用synchronized锁定的锁对象来调用wait方法
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
5.总结:
要保证你调用的wait、notify ,notifyAll的对象,是你synchronized 的对象。
重点:wait,notify,notifyAll这几个方法必须在synchronized即有锁状态下调用,任何对象上调用这些方法的当前线程都应该具有对象监视器,否则它将抛出java.lang.IllegalMonitorStateException