HandlerThread原理和超级细节

首先明白:synchronized,是内置在jvm的内置锁

synchronized 的互斥访问机制。能修饰方法,代码块。

@Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }

        boolean wasInterrupted = false;

        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    wasInterrupted = true;
                }
            }
        }

上面的两段代码可知 HandlerThread 是互斥的。

其中,getlooper()如果先触发,进入synchronized代码段后,回用while循环判断,进行wait()等待。wait()的作用是等待别人使用锁----会让线程挂起,释放锁,然后run()方法执行完里的 notifyAll() 通知挂起的线程---wait结束

 

1.为什么用wait,不用sleeo。

wait 是挂起,释放对象锁。

sleep是不会释放对象的。

2.为什么用notifyAll() ,不用notify()

notifyAll()对所有线程通知。实际情况,不知道有多少个地方都在wait。

notifyAll()和wait不是一一对应的。wait会立刻交出锁,立刻执行,但是notifyALL通知 wait等到锁锁里的内容完成。所以上面代码里的notifyAll 和 mLooper = Looper.myLooper(); 交换顺序没有影响

3.为什么用while不用if?

 实际场景中,使用if只有一次。必须保证m looper非空

  • 13
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆咖啡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值