概述
上一节主要是对Handler的机制简单的概括一下。 Android 消息机制--Handler运行机制(一)这一节主要围绕着Handler来分析Android消息机制。主要包括四点:ThreadLocal、MessageQueue、Looper、Handler的工作原理。
接下来我们就对这4个原理进行深入的理解吧。
一、ThreadLocal 原理
ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储后,只有在指定的线程中可以获取存储的数据,则其他线程无法获取到数据。在日常开发中,用到ThreadLocal的地方很少,但是在一些特点的场景下,通过ThreadLocal可以轻松地实现一些看起来很复杂的功能。比如对于Handler来说,它需要获取当前线程的Looper对象,但很显然Looper的作用域就是线程且不同线程具有不同的Looper对象。这个时候使用ThreadLocal可以很好的实现Looper在线程中的存取。咱们可以假象一下,如果没有ThreadLocal,那么系统就必须提供一个全局的哈希表功Handler查找指定线程的Looper,那么就必须提供一个类似于LooperManager的类,但是系统并没有提供。而是选择了ThreadLocal。这就是ThreadLocal的好处。下面我们来看一下ThreadLocal的内部实现。ThreadLocal是一个泛型类,它的定义为public class ThreadLocal<T>,只要弄清ThreadLocal的get和set方法就可以明白它的工作原理了。首先先看一个它的set方法:
/**
* Sets the value of this variable for the current thread. If set to
* {@code null}, the value will be set to null and the underlying entry will
* still be present.
*
* @param value the new value of the variable for the caller thread.
*/
public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}
在上面的set方法中,首先会通过values方法来获取当前线程中的ThreadLocal数据,如何获取呢?在Thread类的内部有一个成员专门用于存储线程的ThreadLocal的数据:ThreadLocal.Values localValues,因此获取当前线程的ThreadLocal数据就很简单,如果localValues数据为null,那么就需要对其初始化,初始化后在将ThreadLocal的值进行存储。那localValues又是怎么存储的呢。在localValues内部有一个数组,private Object[] tables ,localValues的值就是存在这个数组中。下面来看一下put方法的源码
/**
* Sets entry for given ThreadLocal to given value, creating an
* entry if necessary.
*/
void put(ThreadLocal<?> key, Object value) {
cleanUp();
// Keep track of first tombstone. That's where we want to go back
// and add an entry if necessary.
int firstTombstone = -1;
for (int index = key.hash & mask;; index = next(index)) {
Object k = table[index];
if (k == key.reference) {
// Replace existing entry.
table[index + 1] = value;
return;
}
if (k == null) {
if (firstTombstone == -1) {
// Fill in null slot.
table[index] = key.reference;
table[index + 1] = value;
size++;
return;
}
// Go back and replace first tombstone.
table[firstTombstone] = key.reference;
table[firstTombstone + 1] = value;
tombstones--;
size++;
return;
}
// Remember first tombstone.
if (firstTombstone == -1 && k == TOMBSTONE) {
firstTombstone = index;
}
}
}
上面的代码就实现了存储的功能。具体的我也看不懂,大家有兴趣可以了解里面的算法。其实,我们可以看到下面这两行代码:
table[firstTombstone] = key.reference;
table[firstTombstone + 1] = value;
可以看到ThreadLocal的值在数组中的存储位置总是为ThreadLocal的reference字段所标识的对象的下一个位置。
上面分析了set方法,接下来分析get方法:
/**
* Returns the value of this variable for the current thread. If an entry
* doesn't yet exist for this variable on this thread, this method will
* create an entry, populating the value with the result of
* {@link #initialValue()}.
*
* @return the current value of the variable for the calling thread.
*/
@SuppressWarnings("unchecked")
public T get() {
// Optimized for the fast path.
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values != null) {
Object[] table = values.table;
int index = hash & values.mask;
if (this.reference == table[index]) {
return (T) table[index + 1];
}
} else {
values = initializeValues(currentThread);
}
return (T) values.getAfterMiss(this);
}
/**
* Provides the initial value of this variable for the current thread.
* The default implementation returns {@code null}.
*
* @return the initial value of the variable.
*/
protected T initialValue() {
return null;
}
可以发现,ThreadLocal的get方法逻辑很简单,它同样是去除当前的线程的localValues对象,如果对象为null那么就返回初始值,初始值就是initializeValues()来决定的。默认情况为null。当然咱们也可以重写这个方法。如果ThreadLocal对象不为null,那就取出它的table数组并找出ThreadLocal的reference对象在table数组中的位置,然后table数组中的下一个位置所存储的数据就是ThreadLocal的值。
从ThreadLocal的set和get方法可以得出结论:它们所操作的对象都是当前线程的localValues对象的table数组,因此在不同线程中访问同一个ThreadLocal的set和get方法,它们对ThreadLocal所作的读写操作权限于各自线程的内部。这就是ThreadLocal可以在多个线程中互不干扰地存储和修改数据。
二、MessageQueue原理
消息队列在Android中指的是MessageQueue,MessageQueue主要有2个操作,插入和读取(删除)。插入和读取对应的方法:enqueueMessage和next.enqueueMessage作用是往消息队列中插入一条消息,next的作用则是从消息队列中取出一条消息并将其从消息队列中移除。尽管MessageQueue叫消息队列,但是它的内部实现并不是用的队列,实际上它是通过一个单链表的数据结构来维护消息列表。因为链表在插入和删除上有优势。下面我们来看一下源码:
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("MessageQueue", 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;
}
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 (false) Log.v("MessageQueue", "Returning message: " + msg);
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("MessageQueue", "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;
}
}
源码中我们可以看到enqueueMessage主要是对链表的插入操作。next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法就阻塞在这里,当有新消息到来时,next方法会返回这条消息并将其在链表中删除。
三、Looper原理
Looper是Android消息机制里面的消息循环扮演者,具体的说它会不停地从MessageQueue中查看是否有新消息,如果有新消息就会立刻处理,否则一直阻塞在那里。我们来看一下Looper的构造方法,在构造方法中它会创建一个MessageQueue.然后用线程的对象保存起来。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
我们知道Handler的工作需要Looper,没有Looper线程就会报错。所以第一步就是创建一个looper对象。通过Looper.prepare()就可为当前线程创建一个Looper对象,在通过Looper.loop()来开启消息循环。其主要方法就是loop()。源码如下:
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
Looper的loop方法的工作过程很简单,loop方法是一个死循环。唯一跳出循环的方式就是MessageQueue的next()返回null。当Looper的quit方法被调用时,Looper就会调用MessageQueue的quit或者quitSafely方法来通知消息队列退出,当消息队列被标记为退出状态时,它的next方法就会返回null。也就是说,Looper必须退出。否则loop方法就会无限循环下去。loop方法会调用MessageQueue的next方法来获取新消息。而next()也是一个阻塞操作,当没有消息时,就会一直阻塞在那里。这也导致了loop方法一直阻塞在那里。如果有消息了,next方法就会返回新消息,Looper就会处理这条消息,msg.target.dispatchMessage(msg),msg.target就是发送消息的Handler对象,这样Handler发送的消息最终又交给它的dispatchMessage方法来处理了,但是这里不同的是,Handler的dispatchMessage方法是在创建Handler时所使用的Looper中执行的,这也就成功的将代码逻辑切换到指定的线程中去执行了。
四、Handler原理
Handler的工作主要是发送消息和接受消息,发送消息可以通过post的一系列方法以及send的一系列来实现,post的一系列方法最终是通过send的一系列方法来实现的。
我们可以看一下Handler的发送消息的源码:
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
从源码中,可以发现Handler发送消息的过程就是向消息队列中插入了一条消息,而MessageQueue的next方法就会返回这条消息给Looper,Looper收到消息后就开始处理了。最终消息由Looper交给了Handler处理,这时Handler的dispatchMessage方法会被调用,这时Handler就进入了处理消息的阶段。
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
最后交给了还是Handler的handleMessage(msg)来处理消息。在日常开发中,大家基本都是派生一个Handler的子类并重写handleMessage方法来处理具体的消息。
终于写完了。上周大家对消息机制了解还不怎么透彻,这周从源码上带着大家分析理解。在面试的时候大家可以从源码上去分析去给你的面试官讲解你的理解。是不是和你干讲一些文字有用吧。当然我对这些源码也是一知半解,有兴趣的朋友,可以深入了解!