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.
     * <p>
     * Causes the handler thread's looper to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * 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.
     * </p><p class="note">
     * 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.
     * </p>
     *
     * @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.
     * <p>
     * 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.
     * </p><p>
     * 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.
     * </p><p>
     * 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.
     * </p>
     *
     * @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运行完就被销毁的命运。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容