簡介
Android開發中對Handler、HandlerThread可以說是耳熟爲詳了.
看到HandlerThread很快就會聯想到Handler。Handler在Android中一般都用於在UI主線程中執行,因此在Handler接收消息後,處理消息時,不能做一些很耗時的操作,否則將出現ANR錯誤。
Android中專門提供了HandlerThread類,來解決該類問題。HandlerThread類是一個線程專門處理Hanlder的消息,依次從Handler的隊列中獲取信息,逐個進行處理,保證安全,不會出現混亂引發的異常。HandlerThread繼承於Thread,所以它本質就是個Thread。與普通Thread的差別就在於,它有個Looper成員變量.
使用示例
handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
final Handler handler = new Handler(handlerThread.getLooper());
//執行一個異步任務
handler.post(new Runable());
//發送異步執行消息
handler.sendMessage();
接下來我們從HandlerThread的角度來解析一下Handler的工作原理和HandlerThraed之間的引用關係.
HandlerThread
看看官方的對他的講解
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.
大致意思就是說HandlerThread可以創建一個帶有looper的線程。looper對象可以用於創建Handler類來進行來進行調度
我們從源碼分析一下
package android.os;
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
}
可以看到HandlerThread實際上就是繼承於Thread
線程run()方法當中先調用Looper.prepare()初始化Looper,最後調用Looper.loop(),這樣我們就在該線程當中創建好Looper。
常用的Api
/用於返回與該線程相關聯的Looper對象
handlerThread.getLooper();
//獲得該線程的Id
handlerThread.getThreadId();
//結束當前的Looper 循環。
handlerThread.quit();
//用於looper取出的消息處理
handlerThread.run();
Looper
Lopper的講解重點圍繞prepare和loop兩個函數
prepare
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
ThreadLocal相信大家已經不陌生了,ThreadLocal在多線程環境下,可以保證各個線程之間的變量互相隔離、相互獨立。簡單一句就是保證在當前線程的值唯一,不與其他線程共享數據.
loop
從單詞字面意思看是循環的意思,在Handler這個體系中looper也一個起到一個循環的作用,不斷的從MessageQueue取出message,然後調用handler處理
從下面的源碼我們可以很清楚的看到Lopper.loop函數中的執行的邏輯
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
//....此處省略部分...
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
//....此處省略部分...
我們可以看到從消息隊列中取出msg直接引用了target,而target就是Handler,這意味着最後分發到Handler中進行處理了
msg.target.dispatchMessage(msg)
Handler
首先我來看看Handler構造函數
/**
* Use the provided {@link Looper} instead of the default one.
*
* @param looper The looper, must not be null.
*/
public Handler(Looper looper) {
this(looper, null, false);
}
public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
當我們創建Handler時就需要提供一個Looper對象,最後會將這個looper的消息隊列引用給到Handler,handler是如何使用這個隊列的呢,這個我們後面再來觀察一下
我們在看看默認沒有傳遞looper時,handler是如何工作的
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
如果默認不提供的情況下,可以看到這裏取的就是當前線程的looper,所以爲什麼我們在使用handler需要指定爲Looper.getMainLooper,確保Handler的工作機制是在主線程,而非當前線程.
mLooper = Looper.myLooper();
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
post
post在Handler中用來執行一個任務
public final boolean post(Runnable r){
return sendMessageDelayed(getPostMessage(r), 0);
}
上述代碼可以看到Runnable最後都會包裝成一個Message傳遞出去
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
最後enqueueMessage函數會調用MessageQueue中enqueueMessage函數
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
- 1.函數中首先檢測當前的消息隊列是有被handler所引用,檢測消息隊列是否已經標記已經退出了,此時就不會再繼續往下執行了。
- 2.接下來就是匹配上一次執行消息是否爲空,如果爲空並且沒有延時處理的需求,則直接將本次的執行結果賦值給到mMessages
- 3.檢測到消息不爲時,這裏就會循環去獲取上一次的消息所標記的下一個消息的進行匹配,當滿足條件時,將本次的消息標記給上一次的消息
看到這裏可能有點繞,我在看看messageQueue的next函數,其實所做的事情也是時間和消息標記下一個消息的處理
Message next() {
//.....省略一些代碼
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
// Next message is not ready. Set a timeout to wake up when it is ready.
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
// Got a message.
mBlocked = false;
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
return msg;
}
//.....省略一些代碼
}
Message原理
消息池實現原理
消息池實現原理
既然官方建議使用消息池來獲取消息,那麼在瞭解其內部機制之前,我們來看看Message中的消息池的設計。具體代碼如下:
從Message的消息池設計,我們大概能看出以下幾點:
private static final Object sPoolSync = new Object();//控制獲取從消息池中獲取消息。保證線程安全
private static Message sPool;//消息池
private static int sPoolSize = 0;//消息池中回收的消息數量
private static final int MAX_POOL_SIZE = 50;//消息池最大容量
該消息池在同一個消息循環中是共享的(sPool聲明爲static),
消息池中的最大容量爲50,
從消息池獲取消息是線程安全的。
從消息池中獲取消息
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
從上述代碼中,我們可以瞭解,也就是當前 消息池不爲空(sPool !=null)的情況下,那麼我們就可以從消息池中獲取數據,相應的消息池中的消息數量會減少。消息池的內部實現是以鏈表的形式,其中spol指針指向當前鏈表的頭結點,從消息池中獲取消息是以移除鏈表中sPool所指向的節點的形式。
總結
以上的講解,相信對Handler工作原理以及Handler和HandlerThread之間的工作流程有一定理解了.
Handler、HandlerThread、Looper、Message之間的關係可以總結爲如下圖