HandlerThread

  • 是什么
/**
 * Handy class for starting a new thread that has a looper. The looper can then be 
 * used to create handler classes. Note that start() must still be called.
 */

一个带有looper的线程
有了looper就可以新建绑定此looper的handler


  • 原理
    看下线程的run方法:
    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

1.创建了此线程的looper:Looper.prepare()
2.启动looper循环: Looper.loop();

这部分可参见:

其中:

    /**
     * Call back method that can be explicitly overridden if needed to execute some
     * setup before Looper loops.
     */
    protected void onLooperPrepared() {
    }

  • 两个重要接口:获取looper以及获取绑定此looper的handler:
    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;
    }

在上文的run方法中有:

        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }

此处做了线程同步以及堵塞等处理,需要注意!

获取handler:

    @NonNull
    public Handler getThreadHandler() {
        if (mHandler == null) {
            mHandler = new Handler(getLooper());
        }
        return mHandler;
    }

你可能感兴趣的:(HandlerThread)