记录一次: object not locked by thread before notifyAll()
错误日志:
- 使用继承Thread方式(内部类)
public class MainActivity extends AppCompatActivity {
//...省略...//
class MyThread extends Thread{
@Override
public void run() {
super.run();
//准备消息队列
Looper.prepare();
//获取这次的是否处于loop,第一次时应为null
myLooper = Looper.myLooper();
notifyAll();
Looper.loop();
}
public Looper getLooper(){
if (!isAlive()){
return null;
}
//因为无法确保上述方法哪个方法先运行
//如果先运行的为getLooper的话先让其等待一下
synchronized (this) {
if (isAlive() && myLooper == null){
try {
wait();
} catch (InterruptedException e) {
}
}
}
return myLooper;
}
}
- 开启线程
myThread = new MyThread();
myThread.start();
- 解决方式
class MyThread extends Thread{
@Override
public void run() {
super.run();
//准备消息队列
Looper.prepare();
//保证与wait使用的是同一个的对象监视器
synchronized (this) {
myLooper = Looper.myLooper();
//唤醒主线程
notifyAll();
}
Looper.loop();
}
总结:调用wait能让当前的线程阻塞,使用notifyAll能够唤醒当前对象,并且当前线程必须拥有此对象的monitor()锁。在内部类中的场景下,我使用相同的同步代码块解决了问题。