异步消息处理线程
对于普通的线程而言,执行完run()方法内的代码后线程就结束。而异步消息处理线程是指,线程启动后会进入一个无限循环体之中,每循环一次,从其内部的消息队列中取出一个消息,并回调相应的消息处理函数,执行完一个消息后继续循环。如果消息列表为空,线程会暂停,直到消息队列中有新的消息。
异步线程的实现思路
- 每个异步线程内部包含一个消息队列,队列中的消息一般采用排队机制,先到达的消息会先处理。
- 线程的执行体中使用while(true)进行无限循环,循环体中从消息队列中取出消息,并根据消息的来源,回调响应的消息处理函数。
- 其他外部线程可以向本线程的消息队列发送消息,消息队列内部的读写操作必须进行加锁,不能同时进行读/写操作。
Android 消息机制
Android消息机制主要指Handler的运行机制,Handler的运行机制需要底层的MessageQueue和Looper的支持。
ThreadLocal
ThreadLocal 是一个线程内部存储类,通过它可以在指定的线程中存储数据,同样只能在指定的线程里获取存储的数据,其他的线程无法获取。例如对于Handler来说,它需要获取当前线程的Looper,Looper的作用域就是线程中,并且不同的线程有不同的Looper。
存储数据
<pre>
public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}
Values values(Thread current) {
return current.localValues;
}
Values initializeValues(Thread current) {
return current.localValues = new Values();
}
</pre>
意思是先去获取当前线程的Values,null话会新建一个。这里这个Values是Thread的一个内部类,这个内部类里有一个数组
<pre>
/**
* Map entries. Contains alternating keys (ThreadLocal) and values.
* The length is always a power of 2.
*/
private Object[] table;
</pre>
注释说存储交替的key(ThreadLocal的引用)和values,这个数组的长度始终是2的幂。
然后是values.put
<pre>
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;
}
}
}
</pre>
这里所做的操作验证了刚才的注释,put时ThreadLocal reference的位置始终在value的前一个,这样就把这种键值对交替的存在Thread.values里的Object[] table这个数组里。这样一方面也说明了一个Thread里可以存多个ThreadLocal 和 Value的组合。
获取数据
<pre>
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);
}
</pre>
和存相反,这里先通过当前ThreadLocal的引用获取当前ThreadLocal在table数组的位置,那么他的下一个位置就是之前存入的数据的位置,这样就可以获取数据了。
总结一下:一个Thread里的Values包含一个Obj数组,这个数组的存取是通过ThreadLocal这个类,存时用ThreadLocal的引用作为key,要存的数据做value,取同样,多个ThreadLocal存如同一个Thread的Values的obj数组,获取数据互不影响。验证了ThreadLocal的存取操作仅限于线程里。
MessageQueue
MessageQueue消息队列主要包含两个操作:插入和读取。
插入:
<pre>
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;
}
</pre>
这个方法事件就是根据时间做入队的操作。
在hanlder里发送消息,最后都走了这个方法:
<pre>
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
boolean sent = false;
MessageQueue queue = mQueue;
if (queue != null) {
msg.target = this;
sent = queue.enqueueMessage(msg, uptimeMillis);
}
else {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
}
return sent;
}
</pre>
可以看见这个方法都是调用了MessageQueue的enqueueMessage方法,其中msg参数就是我们发送的Message对象,而uptimeMillis参数则表示发送消息的时间,它的值等于自系统开机到当前时间的毫秒数再加上延迟时间,如果你调用的不是sendMessageDelayed()方法,延迟时间就为0,然后将这两个参数都传递到MessageQueue的enqueueMessage()方法中。
然后是读取的next方法:
<pre>
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;
}
}
</pre>
这个方法非常的长,还调用了ndk,大体的意思就是从消息队列里不停的读Message,当前时间大于Message的when就会返回这个Message,否则一直会阻塞,跳出阻塞的条件是:
<pre>
if (mQuitting) {
dispose();
return null;
}
</pre>
Looper
Looper作用是不停地从MessageQueue中查看是否有消息,有消息就会立即处理。下面看它的两个方法。
prepare:
<pre>
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));
}
</pre>
结合ThreadLocal的分析,这个prepare的操作实际就是在当前线程中存一个Looper。
loop:
<pre>
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();
}
}
</pre>
loop中有个死循环去调用MessgeQueue的next方法,当next返回的message为null时才会跳出死循环,结合对next分析我们知道,MessageQueue的msg为空时会一直阻塞,只有if(mQuitting)才会返回null,这时Looper也会跳出死循环,我们可以通过Loop的quit方法,这个quit方法会调用MessgeQueue的quit给mQuitting设置为true。如果这个有message,会走msg.target.dispatchMessage(msg)方法。
我们来看一下这个target是什么进入Message类:
<pre>
/package/ Handler target;
</pre>
这个target就是hanlder。
Handler
<pre>
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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
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);
}
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
</pre>
看了这两个方法,我脑子已经有一个画面了:
总结
通过Handler发送消息时,new Hanlder时会检查当前当前线程是否有Looper,没有就会报错
"Can't create handler inside thread that has not called Looper.prepare()");
Looper.prepare事件是利用ThreadLocal给当前线程存一个Looper,并通过Looper.Loop获取并启动他。handler发送的消息实际最后都会调用MessageQueue的enQueue的操作,这里会按时间排序,Looper启动后会不停的读取MessgeQueue.next的msg,时间达到的Msg就会被分发,调用handler.dispatchMessage方法,这里实际就是去调用在hanlderMessage()里所编写的业务代码,这样就成功的讲代码切换到Looper.pre里赋值的线程中执行
Tips
另外除了发送消息之外,我们还有以下几种方法可以在子线程中进行UI操作:
- Handler的post()方法
- View的post()方法
- Activity的runOnUiThread()方法