Handler概念:Handler是android提供的一套ui更新机制,也是一套消息处理的机制
ThreadLocal是一个线程的内部存储类,通过它可以在指定的线程中存储数据,数据存储后,只有在指定的线程才能拿到数据,对于其他线程来说则无法获取数据
先看一段代码:
private ThreadLocal mThreadLocal = new ThreadLocal<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mThreadLocal.set(true);
Log.d("demo", mThreadLocal.get() + "");
new Thread("thread1") {
@Override
public void run() {
mThreadLocal.set(false);
Log.d("demo", mThreadLocal.get() + "");
}
}.start();
new Thread("thread2") {
@Override
public void run() {
Log.d("demo", mThreadLocal.get() + "");
}
}.start();
}
返回结果是
true
false
null
这段代码说明了,各个线程对ThreadLocal的操作仅限于各自线程内部,互补干扰,具体ThreadLocal内部怎么实现了,不在本博客内
mHandler.sendMessage(Message.obtain());
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
我们看到是调用了sendMessageDelayed
这个方法,接着跟进去
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);
}
这里可以看到,最终是走到queue.enqueueMessage(msg, uptimeMillis);
这里,是使用MessageQueue的插入方法将消息插入到队列中
这里有一个很重要的点msg.target = this;
留到后面解决,可以设为问题1?
然后就是消息的插入
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;
}
从enqueueMessage的实现来看,它的主要操作就是单链表的插入操作
为什么会采取单链表的设计呢?
这是因为它不停的接受和处理消息,需要进行大量的增删,根据message的时间对message进行插入操作
总结:通过这一系列操作,我们就完成了消息的插入队列,总结一句话:消息根据消息的时间,决定在队列的位置
Message next() {
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;
}
}
源码很长,实际上next是个无限循环的方法,如果消息队列没有消息,就会阻塞在这里,如果有消息来临,就会返回这条消息并在列表中删除
注意点2:nativePollOnce(ptr, nextPollTimeoutMillis);
留到后面解决,可以设为问题2?
取出消息的方法有了,那么是在哪里调用它的呢?
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;
...
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
...
这个方法很长,这里只留下最关键的几行
关键1:final Looper me = myLooper();
方法
跟进:
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
可以看到,这里通过TreadLocal去获取Looper对象,前面讲过TreadLocal的作用,他是为了保持各线程数据的独立性,首先去获取:Looper对象,如果没有获取到,直接抛异常出去
这里多提一点,我们都知道在子线程,如果要使用handler,就必须手动的创建Looper,创建Looper的方法如下
public static void prepare() {
prepare(true);
}
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构造函数
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以看到,looper里面维护这消息队列对象,这样也就保证了消息队列的唯一性;
这里需要注意:Looper.prepare()只可以调用一次,如果调用多次会抛异常
可以看到,创建新的looper对象时,会put进TreadLocal里面,这样就保证了,looper对象在线程里面的唯一性
关键点2:Message msg = queue.next();
方法
死循环的第一步就是去获取消息,而我们全面分析过queue.next()这个方法,他内部也是一个死循环,不停的取出消息到loop方法来处理;
关键点3:
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
唯一能够让loop方法的死循环跳出来的条件是msg==null,那么什么情况下,会msg返回为null呢?
looper里面有个quit()方法,当调用这个方法的时候,就会调用消息队列的quit()方法,这是消息队列就会被标记为退出状态,它的next()方法就会返回null,而loop()方法接受到null之后,就会退出循环;所以如果在子线程中我们手动的创建looper,那么在所有消息处理完毕之后,我们就需要退出这个looper,就调用这个方法;
关键点3:msg.target.dispatchMessage(msg);
方法
这个方法就是处理消息的分发,将消息发送给指定的handler,我们首先来看一下target是什么东西;
他是message对象里面的一个属性Handler target;
一个线程中,looper和队列都是唯一性的,handler是可以无限制创建的,我们怎么保证发送和接受的是同一个handler呢,就是靠这个属性,和问题1类似
loop()方法获取到消息后,通过msg.target.dispatchMessage(msg);
方法分发出去,我们跟进看怎么分发的
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
我们可以看到,显示判断message有没有callback属性,这个属性又是什么?
查看源码,我们发现是一个Runnable callback;
我们发送消息一般有两种方式,一种sendMessage,一种post(new Runnable)方式,第二种方式就是给message添加一个callback属性,这里会判断是否有这个属性,如果有,就会走handCallback()方法
private static void handleCallback(Message message) {
message.callback.run();
}
就是会回调到我们的run()方法里面
如果没有callback(),就是handleMessage()方法,也就是我们创建handler时,实现的handMessage方法,至此,一个完整的消息发送和接受就走了一遍
问题1:多个handler发送消息,我们是怎么找到对应的handler去处理?
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
在我们将消息插入队列的时候,会将handler的引用传递给message.target,分发的消息的时候,会发送给message.target的方法
问题2:为什么消息队列死循环不会引起程序卡死?
首先这里有两个概念是不一样的,死循环和ANR的区别
ANR:程序无响应:是主线程做了耗时操作,来不及处理下一个事件而引起的;
消息队列的死循环是运用了linux的pipe/epoll机制,主线程的MessageQueue没有消息时,便阻塞在loop的queue.next()中的nativePollOnce()方法里,此时主线程会释放CPU资源进入休眠状态,直到下个消息到达或者有事务发生
为什么要设计死循环机制?
对于线程即是一段可执行的代码,当可执行代码执行完成后,线程生命周期便该终止了,线程退出。而对于主线程肯定不能运行一段时间后就自动结束了,那么如何保证一直存活呢??简单的做法就是可执行代码能一直执行下去,死循环便能保证不会被退出