HandlerThread源码分析

一、HandlerThread简介

  • HandlerThread是什么鬼?
    HandlerThread本身是继承自Thread,所以HandlerThread还是一个Thread
  • 既然还是一个Thread,那HandlerThread还有存在的必要么?
    其实HandlerThread的出现是为了减少对Thread的频繁创建销毁而诞生的,毕竟线程的创建还是很耗资源的,而且频繁的创建销毁也会带来内存的抖动;
  • HandlerThread如何可以减少Thread频繁创建销毁
    其实HandlerThread中帮我们封装了一个Looper对象,通过Looper的机制再配合Handler,就可以减少频繁的使用new Thread()

如果想了解LooperHandler是如何配合的?
可以看下我之前写的两个文章
Handler、Looper、messagequeue源码分析及使用(1)
Handler、Looper、messagequeue源码分析及使用(2)
其中在讲解handler的使用如何创建非UI线程的handler,实现UI线程发送消息通知非UI线程做耗时操作? 这部分完全可以使用HandlerThread搞定。

二、HandlerThread使用

  • HandlerThread使用很简单,用法也和Thread一直,但需要额外创建一个Handler对象【或者调用HandlerThread.getThreadHandler()获取】,通过重写HandlerhandleMessage,或者post(Runnable r)来实现耗时操作,但值得注意的是,在调用HandlerThreadgetLooper()getThreadHandler()之前一定要先start()
  • HandlerThread一个简单的使用案例
public class HandlerThreadTest {
    private final String TAG = this.getClass().getSimpleName();
    private static final int MSG_WHAT = 0x100;

    private HandlerThread handlerThread = null;
    private Handler handler = null;

    public HandlerThreadTest(String name) {
        // 注意顺序
        handlerThread = new HandlerThread(name);
        handlerThread.start();
        handler = new MyHandler(handlerThread.getLooper());
    }

    public void excute() {
        Log.d(TAG, "主线程id=" + Looper.getMainLooper().getThread().getId());
        handler.sendEmptyMessage(MSG_WHAT);
    }

    private class MyHandler extends Handler {

        private MyHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_WHAT) {
                try {
                    // 模拟耗时操作
                    handlerThread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Log.d(TAG, "当前运行线程id=" + Thread.currentThread().getId());
        }
    }

}

上面通过自己创建一个Handler来实现耗时操作,你也可以调用getThreadHandler()获得一个Handler对象,运行结果:

02-08 15:31:51.387 16111-16111/com.ktln.must D/HandlerThreadTest: 主线程id=1
02-08 15:31:54.397 16111-16370/com.ktln.must D/HandlerThreadTest: 当前运行线程id=22899


三、HandlerThread源码分析

关键代码已添加注释

public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    Looper mLooper;
    private @Nullable Handler mHandler;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }
    
    /**
     * Constructs a HandlerThread.
     * @param name
     * @param priority The priority to run the thread at. The value supplied must be from 
     * {@link android.os.Process} and not from java.lang.Thread.
     */
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority; // 设置优先级
    }
    
    /**
     * 在执行Looper.loop()前调用此方法的重载方法,可以用来执行一个初始化操作
     */
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        // 创建Looper对象,以及Looper内的消息队列
        Looper.prepare();
        synchronized (this) {
            // 获取创建的Looper对象,并赋值给mLooper
            mLooper = Looper.myLooper();
            // 通知处于wait的方法,继续执行
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        // 预留方法,可以执行自己的一些初始化操作
        onLooperPrepared(); 
        // 开启对消息队列的轮询
        Looper.loop();
        mTid = -1;
    }
    
    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason isAlive() returns false, this method will return null. If this thread
     * has been started, this method will block until the looper has been initialized.  
     * @return The looper.
     * 这个方法会返回一个跟当前线程关联的Looper对象. 如果当前线程没有调用start方法,或者其他原因使
     * isAlive()返回false, 这个方法将返回null. 
     * 如果当前线程已经start了, 这个方法将堵塞,直到Looper对象被初始化完成。  
     * @return 返回 looper 对象.
     */
    public Looper getLooper() {
        if (!isAlive()) {
            // 如果线程不是活动状态,则返回null
            return null;
        }
        
        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                // 如果线程是活着的,并且mLooper == null,那就处于堵塞状态
                // 此处是等待run方法中的mLooper = Looper.myLooper()赋值完成,并且调用notifyAll()才会激活
                // 被激活后,会再一次执行while的判断,因为这时候mLooper不为null,则跳出循环
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    /**
     * @return a shared {@link Handler} associated with this thread
     * @hide
     */
    @NonNull
    public Handler getThreadHandler() {
        if (mHandler == null) {
            // 如果没有handler对戏,创建一个绑定当前Looper的handler对象。
            // 即:创建了一个为非UI线程服务的handler
            mHandler = new Handler(getLooper());
        }
        return mHandler;
    }

    /**
     * Quits the handler thread's looper.
     * 

* Causes the handler thread's looper to terminate without processing any * more messages in the message queue. *

* Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. *

* Using this method may be unsafe because some messages may not be delivered * before the looper terminates. Consider using {@link #quitSafely} instead to ensure * that all pending work is completed in an orderly manner. *

* * @return True if the looper looper has been asked to quit or false if the * thread had not yet started running. * * @see #quitSafely */ public boolean quit() { Looper looper = getLooper(); if (looper != null) { looper.quit(); return true; } return false; } /** * Quits the handler thread's looper safely. *

* Causes the handler thread's looper to terminate as soon as all remaining messages * in the message queue that are already due to be delivered have been handled. * Pending delayed messages with due times in the future will not be delivered. *

* Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. *

* If the thread has not been started or has finished (that is if * {@link #getLooper} returns null), then false is returned. * Otherwise the looper is asked to quit and true is returned. *

* * @return True if the looper looper has been asked to quit or false if the * thread had not yet started running. */ public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; } /** * Returns the identifier of this thread. See Process.myTid(). */ public int getThreadId() { return mTid; } }

HandlerThread的精髓代码是执行在run()中的,在run()中创建了Looper对象,Looper.loop()开启循环,在通过mLooper创建一个Handler来服务此线程。


总结:
HandlerThread可以帮助我们创建一个服务于子线程的Handler,通过消息机制的方式,来处理耗时操作;这样就可以避免Thread运行完就被销毁的命运。

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