button.setOnClickListener {
handler?.post {
println(Thread.currentThread())
}
handler?.post {
println(Thread.currentThread())
}
}
输出结果:
System.out: Thread[Thread-2,5,main]
System.out: Thread[Thread-2,5,main]
HandlerThread
HandlerThread 是 Android 对Thread的封装,增加了Handler的支持,实现就是实现了前面例子的功能
val handlerThread = HandlerThread(“test”)
handlerThread.start()
handler = Handler(handlerThread.looper)
MessageQueue 源码剖析
我们都知道Handler的功能非常丰富,拥有立刻执行post()
、延迟执行postDelayed()
、定时执行postAtTime()
等执行方式。下面就从源码分析是如何实现的。
public final class 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