android HandlerThread 源码分析

HandlerThread是android提供的线程相关类,它继承自Thread。
为什么要了解它,除了可能会使用到它,还因为我们很多常用的类都有用到HandlerThread类,比如说IntentService,要研究这些类就离不开先了解HandlerThread。
从名字上看HandlerThread肯定还有个Handler进行异步操作。是的,它内部还维护了一个对应线程的Looper对象,为了让该Looper对象绑定该线程理所当然要先运行该线程,也就是执行new HandlerThread().start()方法。当然Looper也就在run()方法中进行了初始化。

//IntentService的run()方法
@Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

很明显主要就是做了个Looper的初始化,所以说,我们在使用HandlerThread时并不能像普通的Thread一样在run()中重写我们想要执行的代码。
那就要问了,我们要在哪里执行代码,HandlerThread到底怎么用。好吧,这个其实很简单,通过handler的一系列send,post方法就会使得你要执行的代码将在子线程运行。

/**
     * @return a shared {@link Handler} associated with this thread
     * @hide
     */
    @NonNull
    public Handler getThreadHandler() {
        if (mHandler == null) {
            mHandler = new Handler(getLooper());
        }
        return mHandler;
    }

由于获取HandlerThread提供的handler的方法是hide状态,所以只能自己创建Handler对象并绑定对应的Looper对象。HandlerThread提供的获取其Looper对象的方法:getLooper()。

    HandlerThread handlerThread = new HandlerThread("YanKong");
    new Handler(handlerThread.getLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            //执行逻辑
            return false;
        }
     });

当然除了下面这种Callback的调用方式还可以,通过继承Handle()的方式重写Handler的handlerMessage的方法,再或者调用post的方式执行代码。这三种方式的区别可以看我的另一篇博客的介绍:https://www.jianshu.com/p/239472319ca4

你可能感兴趣的:(android HandlerThread 源码分析)