HandlerThread源码解析

上一篇文章对HandlerThread的概念及用法做了一个基本的介绍,并且使用HandlerThread改写了相册图片加载模块中的ImageLoader,可以看到,改写后的代码变得更加清晰和简洁了。本篇文章将延续之前的主题,从源代码层面对HandlerThread的底层原理进行深入的剖析,让大家不仅知其然,更知其所以然,好了,话不多说,就让我们开始今天美妙的探索之旅吧_

如果读者已经较好地掌握了Android异步消息处理的底层机制,那么理解HandlerThread的源码将会变得异常简单。对Android异步消息处理底层机制尚未完全掌握的朋友可先阅读我之前的博文Android异步消息处理机制深度解析

HandlerThread源码如下:

  1 /*
  2  * Copyright (C) 2006 The Android Open Source Project
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package android.os;
 18 
 19 /**
 20  * Handy class for starting a new thread that has a looper. The looper can then be 
 21  * used to create handler classes. Note that start() must still be called.
 22  */
 23 public class HandlerThread extends Thread {
 24     int mPriority;
 25     int mTid = -1;
 26     Looper mLooper;
 27 
 28     public HandlerThread(String name) {
 29         super(name);
 30         mPriority = Process.THREAD_PRIORITY_DEFAULT;
 31     }
 32     
 33     /**
 34      * Constructs a HandlerThread.
 35      * @param name
 36      * @param priority The priority to run the thread at. The value supplied must be from 
 37      * {@link android.os.Process} and not from java.lang.Thread.
 38      */
 39     public HandlerThread(String name, int priority) {
 40         super(name);
 41         mPriority = priority;
 42     }
 43     
 44     /**
 45      * Call back method that can be explicitly overridden if needed to execute some
 46      * setup before Looper loops.
 47      */
 48     protected void onLooperPrepared() {
 49     }
 50 
 51     @Override
 52     public void run() {
 53         mTid = Process.myTid();
 54         Looper.prepare();
 55         synchronized (this) {
 56             mLooper = Looper.myLooper();
 57             notifyAll();
 58         }
 59         Process.setThreadPriority(mPriority);
 60         onLooperPrepared();
 61         Looper.loop();
 62         mTid = -1;
 63     }
 64     
 65     /**
 66      * This method returns the Looper associated with this thread. If this thread not been started
 67      * or for any reason is isAlive() returns false, this method will return null. If this thread 
 68      * has been started, this method will block until the looper has been initialized.  
 69      * @return The looper.
 70      */
 71     public Looper getLooper() {
 72         if (!isAlive()) {
 73             return null;
 74         }
 75         
 76         // If the thread has been started, wait until the looper has been created.
 77         synchronized (this) {
 78             while (isAlive() && mLooper == null) {
 79                 try {
 80                     wait();
 81                 } catch (InterruptedException e) {
 82                 }
 83             }
 84         }
 85         return mLooper;
 86     }
 87 
 88     /**
 89      * Quits the handler thread's looper.
 90      * <p>
 91      * Causes the handler thread's looper to terminate without processing any
 92      * more messages in the message queue.
 93      * </p><p>
 94      * Any attempt to post messages to the queue after the looper is asked to quit will fail.
 95      * For example, the {@link Handler#sendMessage(Message)} method will return false.
 96      * </p><p class="note">
 97      * Using this method may be unsafe because some messages may not be delivered
 98      * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
 99      * that all pending work is completed in an orderly manner.
100      * </p>
101      *
102      * @return True if the looper looper has been asked to quit or false if the
103      * thread had not yet started running.
104      *
105      * @see #quitSafely
106      */
107     public boolean quit() {
108         Looper looper = getLooper();
109         if (looper != null) {
110             looper.quit();
111             return true;
112         }
113         return false;
114     }
115 
116     /**
117      * Quits the handler thread's looper safely.
118      * <p>
119      * Causes the handler thread's looper to terminate as soon as all remaining messages
120      * in the message queue that are already due to be delivered have been handled.
121      * Pending delayed messages with due times in the future will not be delivered.
122      * </p><p>
123      * Any attempt to post messages to the queue after the looper is asked to quit will fail.
124      * For example, the {@link Handler#sendMessage(Message)} method will return false.
125      * </p><p>
126      * If the thread has not been started or has finished (that is if
127      * {@link #getLooper} returns null), then false is returned.
128      * Otherwise the looper is asked to quit and true is returned.
129      * </p>
130      *
131      * @return True if the looper looper has been asked to quit or false if the
132      * thread had not yet started running.
133      */
134     public boolean quitSafely() {
135         Looper looper = getLooper();
136         if (looper != null) {
137             looper.quitSafely();
138             return true;
139         }
140         return false;
141     }
142 
143     /**
144      * Returns the identifier of this thread. See Process.myTid().
145      */
146     public int getThreadId() {
147         return mTid;
148     }
149 }

代码不多,算上注释才149行。
HandlerThread中最重要的是它的run方法和getLooper方法,我们先来看run方法:
首先扫一眼run方法,突然感觉好熟悉啊!熟悉的Looper.prepare(),熟悉的Looper.loop(),这不是我们在子线程创建Handler时所需要的一些操作吗?没错,虽然我们在当前的run方法里并没有创建Handler,但是读完本文,你应该能体会到它和我们在子线程创建Handler的异曲同工之妙。
在run方法中,首先会去调用Looper.prepare(),Looper.prepare()会去检查sThreadLocal中是否存储了Looper对象,若已经存储了,则报异常(一个线程最多只能有一个Looper对象),若尚未存储,则新建一个Looper对象并将其放入sThreadLocal中。之后会进入一个同步代码块,取出当前的Looper对象赋给HandlerThread对象的成员变量mLooper并调用notifyAll()方法。接着便会去调用Looper.loop(),在Looper.loop()中有一个死循环,会不断地从MessageQueue中取出下一条消息,如果拿不到消息则阻塞。拿到消息后,如果消息不为空且消息的target属性不为空,则调用消息的target属性的dispatchMessage方法。

再来看getLooper方法,首先会调用isAlive()方法测试线程是否还活着,如果不是,则直接返回null。接着会进入一个同步代码块,当线程还存活着且成员变量mLooper为null时,会执行wait操作,等待run方法中的notifyAll(),由此可知,只要之前我们的HandlerThread被启动了,这个方法会一直阻塞直至mLooper初始化完成,最后将初始化完成的mLooper返回出去。

通常情况下,HandlerThread启动后,会通过getLooper()方法取出Looper对象并将其作为Handler的初始化参数。此时,getLooper()方法是运行在主线程的,而Looper对象的初始化是位于子线程(HandlerThread)的run方法中的,getLooper()方法中的 wait()与run方法中的notifyAll()共同协作,实现了两个线程之间的同步。

到这里,相信大家对HandlerThread的源码已经有了一个非常深入的理解了,下一篇文章将介绍与HandlerThread关联甚大的IntentService,大家一起期待吧!

参考:http://blog.csdn.net/lmj623565791/article/details/47079737

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

推荐阅读更多精彩内容