Looper getMainLooper 和 Looper.mylooper 的区别

looper.mylooper 实质就是取当前线程的looper,这个Looper在prepare的时候创建并通过threadLocal存储起来的:

Looper中维护了一个final static的 sThreadLocal。

不清楚的ThreadLocal实质的我写了一篇自己的理解:对ThreadLocal的一点自己的理解

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }    

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

getMainLooper是取主线程的looper

    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }    

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

从上面可以看出来getMainLooper取得是sMainLooper,sMainLooper是static的。而sMainLooper是在prepareMainLooper中调用 sMainLooper = myLooper();本质获取当前线程的looper又因为prepareMainLooper是在主线程ActivityThread中调用的所以是主线程通过静态变量sMainLooper保存的.

面试问:主线程的looper能不能退出 ,handlerThread的线程能不能退出

其实看这个方法的 quitAllowed参数,主线程这个参数是false调用的是prepare(false),handlerThread调用的是prepare():

    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }   


 MessageQueue(boolean quitAllowed) {
        mQuitAllowed = quitAllowed;
        mPtr = nativeInit();
    }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值