上篇文章分析了Handler消息機制,這篇文章就分析Looper MessageQueue Handler 之間的調用關系
Looper的創建
- 首先看下ActivityThread的main()函數:
public static void main(String[] args) {
........................................................
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
}
- 進入Looper.prepareMainLooper();
public final class Looper {
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;
//創建Looper
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//將Looper創建變存入sThreadLocal
sThreadLocal.set(new Looper(quitAllowed));
}
public static void prepareMainLooper() {
prepare(false);//創建Looper
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();//取出Looper
}
由上代碼可以看出主線程中的Looper是通過sThreadLocal獲取的 那么ThreadLocal這個類是干什么的呢 我們去源碼看看
public class ThreadLocal<T> {
//獲取Looper
public T get() {
Thread t = Thread.currentThread();//獲取當前線程
ThreadLocalMap map = getMap(t);//根據當前線程ThreadLocalMap
if (map != null) {
//通過當前線程為key獲取Looper
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
//保存Looper
public void set(T value) {
Thread t = Thread.currentThread();//獲取當前線程
ThreadLocalMap map = getMap(t);//根據當前線程ThreadLocalMap
if (map != null)
map.set(this, value);//以當前線程作為key Looper作為value保存
else
createMap(t, value);
}
//初始化 ThreadLocalMap
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
//根據線程獲取ThreadLocalMap
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//ThreadLocalMap 其本質就是一個HasMap 但是卻比HasMap更優化 其散列更均勻
static class ThreadLocalMap {
}
}
通過分析ThreadLocal 就知道了其內部有一個ThreadLocalMap散列表 通過獲取當前線程作為key Looper作為Value存儲 這樣的好處有哪些呢
- 保證Looper的線程安全 相當于同步鎖 因為在同一線程下Looper只有一個(HasMap存儲原理 key相同 value不同 就替換Value的值)
- 節省不必要的內存開支,無論你在客戶端創建多少個Handler 但是該線程下的Looper只有一個
** Handler與Looper的關聯**
- 由上面看到了Looper在ActivityThread的main()函數通過Looper.prepareMainLooper()就創建好了 那么Handler又是如何與之相聯的呢
public class MainActivity extends AppCompatActivity {
//平時一般的寫法
private Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
}
public class Handler {
final Looper mLooper;
//Handler構造
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
。。。。。。
//Looper就在這里與Handler關聯了
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//獲取消息列表
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
public final class Looper {
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
}
現在分析下就知道了 由于我們的Handler在主線程創建的 那么時候其關聯的就是Looper.prepareMainLooper()所創建的Looper 同理MessageQueue也是一樣 在Looper創建的時候也一同創建了
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
......
}
MessageQueue的入隊和出隊
- Handler通獲取Looper中MessageQueue 發送消息的時候將消息插入MessageQueue隊列并進行以處理時間排序
//handler發送消息
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);
}
//將消息入隊
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
//MessageQueue插入消息msg 并以when排序 這里涉及數據結構和算法 不做過多分析
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;
}
- 從MessageQueue取出消息
//取出消息 請結合MessageQueue整體源碼分析
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
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;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
if (mQuitting) {
dispose();
return null;
}
// If first time idle, then get the number of idlers to run.
// Idle handles only run if the queue is empty or if the first message
// in the queue (possibly a barrier) is due to be handled in the future.
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
// No idle handlers to run. Loop and wait some more.
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
// Run the idle handlers.
// We only ever reach this code block during the first iteration.
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null; // release the reference to the handler
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
// Reset the idle handler count to 0 so we do not run them again.
pendingIdleHandlerCount = 0;
// While calling an idle handler, a new message could have been delivered
// so go back and look again for a pending message without waiting.
nextPollTimeoutMillis = 0;
}
}
最后
由上面分析知道了Handler Looper MessageQueue之間是如何協作的 但是都是在主線程中使用的 那么如何在分線程中使用Handler Looper呢 其實在Looper的源碼注釋中已經給了答案
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();//創建Looper
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();//開啟循環
}