HandlerThread继承于Thread类,所以是一个线程类,它存在的价值是什么呢?

答案就是,HandlerThread可以创建一个自带Looper的线程,自动处理Looper创建时的同步问题

public class HandlerThread extends Thread {

    @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;
        }

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

}

关键点就在这两个方法中的synchronized同步块,wait和notifyAll协作使用,保证了mLooper创建的同步。例如,在UI线程中创建了HandlerThread线程对象,并通过getLooper方法获取该线程的Looper,如果mLooper为null,并且线程alive的话,会一直等待直到mLooper实例化结束,自动完成线程同步
getLooper之前,需要先启动HandlerThread,不然线程处于非启动状态,一直返回空Looper对象。


原文链接:https://blog.csdn.net/qinhai1989/article/details/82153604

 

posted on 2020-04-26 14:40  青年程序猿  阅读(447)  评论(0编辑  收藏  举报