记录一次: object not locked by thread before notifyAll()

文章讲述了在Android应用中,使用继承Thread的内部类时遇到objectnotlockedbythreadbeforenotifyAll错误,解决方法是确保在调用wait和notifyAll时,线程对同一对象持有锁。作者通过同步代码块解决了问题并分享了经验。
摘要由CSDN通过智能技术生成

记录一次: object not locked by thread before notifyAll()

错误日志:
XX

  1. 使用继承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;
        }
    }
  1. 开启线程
        myThread = new MyThread();
        myThread.start();
  1. 解决方式
class MyThread extends Thread{
        @Override
        public void run() {
            super.run();
            //准备消息队列
            Looper.prepare();
            //保证与wait使用的是同一个的对象监视器
            synchronized (this) {
                myLooper = Looper.myLooper();
                //唤醒主线程
                notifyAll();
            }
            Looper.loop();
        }

总结:调用wait能让当前的线程阻塞,使用notifyAll能够唤醒当前对象,并且当前线程必须拥有此对象的monitor()锁。在内部类中的场景下,我使用相同的同步代码块解决了问题。

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值