HandlerThread

说起HandlerThread我的确没怎么用到过,以至于面试的时候被面试官问起时也是完全不知道。所以,今天就来补一补这个东西。其实这个类也不大,就149行代码。下面就这英文看下意思,当然如果觉得英文烦躁,可以去掉英文就着我蹩脚的翻译暂且看看:


/** 开启一个带有looper的线程,start()方法必须调用(开启线程肯定得调用start()方法啊!)。
 * 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.
 */
public class HandlerThread extends Thread {
    int mPriority;//优先级
    int mTid = -1;//获取调用进程的线程ID
    Looper mLooper;//Looper对象

    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.
     */
     //构造函数:传入一个String 对象做线程的名字,一个int值代表线程优先级。
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }
    
    /**
     * Call back method that can be explicitly overridden if needed to execute some
     * setup before Looper loops.
     */
     //可以重写这个函数做一些准备工作,这个放方法在loop()方法调用之前调用。
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            //唤醒在等待的
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        //在loop()方法调用之前调用
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }
    
    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason is 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.
     */
    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 {
                    //如果Looper未创建好,就先等待,对应上面的notifyAll();
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    /**
     * 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
     */
     //直接退出,调用了looper.quit()方法;
    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.
     */
     //安全退出,调用了quitSafely()方法
    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

    /**
     * Returns the identifier of this thread. See Process.myTid().
     */
     //返回Process.myTid()
    public int getThreadId() {
        return mTid;
    }
}

大体意思:

在一个线程中创建了一个Looper对象,而我们知道Looper对象是消息机制的核心。那我们在子线程中弄这样一个Looper对象就意味着该子线程也能像UI线程那样,通过Handle进行线程之间的切换工作,从某个线程切换到该子线程中来。

那么,它到底有什么好处呢?

场景

我们来想一个场景,如果我们现在需要请求网络数据(假设需要请求一张图片,图片请求返回后需要更新UI),我们都知道UI线程中不允许进行耗时的网络请求。那么,我们通常会开启一个子线程来进行请求:如果你不用网络请求的三方库,一般会通过new Thread。然后start()来完成吧!这样的话,如果有多次请求图片,那么我们就得new 很多个Thread。所以这是个问题!!!

现在你就会想,难道(柯南BGM)你是说。。。没错,HandlerThread可以用来解决这个问题。还有这种骚操作?

问题解决分析

通过上面代码我们知道:HandlerThread一个子线程,并且含有一个Looper。
再来看看那个问题:我们之所以需要new Thread。。然后start().是因为UI线程无法进行网络请求,但是,HandlerThread可是一个子线程。。。重要的说三遍。所以,在它里面可以直接请求网络,于是上面的new Thread 。。 start()问题就解决了。(卧槽。。。这也是骚操作?)。
当然,就凭他是个子线程还没法说服我,虽然它是一个子线程不需要new Thread(),但是它自己也可能需要多次创建啊!只不过是从new一个Thread变成了new HanderThread而已。这还不是没卵用。(这这这。。。)

那么如何解释它不需要重复创建呢?
其实也不难,只需要子线程不结束不就行了。(run方法中加个while(true)啊,呵呵),不过,它这里并不是while(true),而是用到了调用了一个loop()方法。

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

loop方法是阻塞的,所以它后面的语句在它未退出的(可以通过quit()方法和quitSafely()方法退出)时候是没办法执行的。再加上它可以通过在外部实现一个Handler,然后,通过这个Handler给Looper发送message,近而源源不断的实现网络请求。所以,这就真正的解决了上面提出的那个问题。(我墙都不服。。。)

这里给一个连接,里面介绍了如何在外部创建一个Handler,然后源源不断进行网络请求。
链接地址:Android 多线程之HandlerThread 完全详解

总结一下优缺点:

引用一篇文章:

作者:Cooke_
链接:http://www.jianshu.com/p/e9b2c0831b0d
來源:简书

  1. HandlerThread将loop转到子线程中处理,说白了就是将分担MainLooper的工作量,降低了主线程的压力,使主界面更流畅。
  2. 开启一个线程起到多个线程的作用。处理任务是串行执行,按消息发送顺序进行处理。
  3. 相比多次使用new Thread(){…}.start()这样的方式节省系统资源。
  4. 但是由于每一个任务都将以队列的方式逐个被执行到,一旦队列中有某个任务执行时间过长,那么就会导致后续的任务都会被延迟处理。
  5. HandlerThread拥有自己的消息队列,它不会干扰或阻塞UI线程。
  6. 通过设置优先级就可以同步工作顺序的执行,而又不影响UI的初始化;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容