HandlerThread源码解析

2016-04-13  本文已影响184人  伐冰

上一篇文章对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

上一篇 下一篇

猜你喜欢

热点阅读