要了解Handler的工作机制,首先要搞清楚一个线程的私有存储类,ThreadLocal
ThreadLocal的工作原理:
ThreadLocal是一个线程内部的数据存储类,通过他可以在指定的线程中存储数据,数据存储后,只有在指定的线程中才能获取到存储的数据,对于其他线程则不能获取到存储的数据.
ThreadLocal中用一个ThreadLocalMap存储数据,key为当前线程名,所以只有在当前线程才能拿到当前线程的数据
- Thread.get()
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);//第一次map为null
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
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 getMap(Thread t) {
// ThreadLocal.ThreadLocalMap threadLocals = null;
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
- Thread.set()
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
而在Android的消息机制中,每个线程对应一个looper和一个messageQueue,就是用的ThreadLocal来保证
Handler消息机制的主要流程
- 初始化全局唯一的Looper对象,和MessageQueue对象,调用Looper.loop()
- 产生消息
- 发送消息
- 处理消息
- App启动的入口ActivityThread的 main()函数中,开头有一个prepareMainLooper()方法最后有一个Looper.loop()方法.
prepareMainLooper() new了一个Looper对象,并将其保存在sThreadLocal中,在Looper的构造方法中,new了一个MessageQueue对象,赋值给了Looper的mMessageQueue引用.
Looper.loop()开启了一个死循环,不断调用MessageQueue的next()方法,MessageQueue的next()方法调用MessageQueue中
Message的next
Looper.prepareMainLooper();
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
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));//将looper对象存储到MainThread中
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);//Looper类的构造方法中,创建MessageQueue
mThread = Thread.currentThread();
}
Looper.loop()的代码太长了,就不贴了,里面重要的方法就两个,Message msg = queue.next();msg.target.dispatchMessage(msg); 当当前没有要处理的消息时,即nextPollTimeoutMillis 不为0时,系统会去执行mPendingIdleHandlers,即系统内的一些消息,比如GC回收等等,当没有要执行的pending idle handler时,会continue退出当前循环 下一次进入循环,如果nextPollTimeoutMillis !=0,就会进入挂起状态,调用native的nativePollOnce(ptr, nextPollTimeoutMillis); 首先,enqueueMessage方法会拿到我们传入的msg,把msg的when赋值给局部变量when,当msg是一个新的head或者when
在介绍MessageQueue的next()方法之前,首先来了解一下Message
Message是一个对象池的形式,以单链表的方式,来管理消息,对象池的MaxSize为50,也就是说,Handler机制中,最多能保存50个消息
MessageQUeue的next方法,顾名思义,就是取出当前需要处理的一条消息
取出Message.next即消息队列中的下一条消息,赋值给全局变量mMessage,只有当有消息,且mMessage.when<=当前系统时间时,才会返回mMessage,返回message后就是处理message,msg.target.dispatchMessage(msg),这里我们稍后再讲
先看下MessageQueue,next()里面部分源码
当mMessage==null时,会将nextPollTimeoutMillis赋值为-1,当now 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;
}
// 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.没有pendingIdleHandler时,continue
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.
//如果有pending idel handler,执行pending idel handler,然后将nextPollTimeoutMillis 赋值为0
nextPollTimeoutMillis = 0;
直到有新的事物发生,native的nativeWake方法被调用,唤醒当前线程
那么nativeWake方法什么时候被调用呢?
这要从消息的发送讲起
消息发送是通过handler的sendMessage或一些其他的方法,我们以sendMessage()为例,shendMessage方法会调用到Handler的enqueueMessage方法,最后会调到MessageQueue的enqueueMessage方法
下面我们来看MessageQueue的enqueueMessage方法究竟做了写什么呢 msg.markInUse();
//这里将当前消息的when赋值给when
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.
// 这里p==null就是说mMessages==null,即我们传进来的msg是一条message链的head
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) {
//这里是说,当p==null就是到达链表尾部,或者when
然后我们接着来看Looper.loop()方法,当通过MessageQueue拿到当前消息后,会调用msg.target.dispatchMessage(msg);即handler的dispatchMessage方法,这个方法做了什么呢,非常简单,我们看看源码
/**
* Subclasses must implement this to receive messages.
*/
public void handleMessage(@NonNull Message msg) {
}
/**
* Handle system messages here.
*/
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
如果有callback,就调callback,如果没有callback,就直接调用了handlerMessage方法,而这个handleMessage方法在Handler中是一个空实现,具体的实现就是我们new Handler时重写的handleMessage方法.
那么总结一下,Handler机制为什么能做到线程间的消息传递呢?
主线程
Looper.prepare()-->创建Looper和MessageQueue,通过threadLocal将looper和thread以键值对的形式保存在ThreadLocalMap中,一个线程对应一个唯一的looper对象
new Handler-->创建handler,实现handlerMessage方法
Looper.loop()拿到msg,调用msg.target即handler的dispatchMessage(),然后调到handleMessage方法
子线程
new Message-->创建一个msg
handler.sendMessage-->将handler赋值给msg.target,调用messageQueue的enqueueMessage(),这里子线程为什么能拿到主线程的messageQueue呢?首先通过Looper.myLooper()从threadLocal里面获取到mLooper,再拿到mLooper里面的mMessageQueue.