上篇文章分析了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 sThreadLocal = new ThreadLocal();
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 {
//获取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();//开启循环
}