文章目录
1. 从一个最简单的示例开始
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//1.创建handler
Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
//4.处理消息
switch (msg.what) {
case 100:
Log.i("Handler",(String)msg.obj);
break;
}
}
};
//2.创建消息
Message msg = new Message();
msg.what = 100;
msg.obj = "hhhh";
//3.发送消息
handler.sendMessage(msg);
setContentView(R.layout.activity_main);
}
}
备注:上面的代码,不是最佳实践,可能会导致内存泄漏,因为这个Handler是通过匿名内部类来实现的,内部持有当前Activity的this指针,比如,handler.postDelayed(runnable,30_000),在30s后执行runnable,如果还未到30s,用户就退出页面,但持有handler引用的Message还在主线程的MesssageQueue中,这就会导致内存泄漏。所以,最好将Handler定义为静态内部类+弱引用来处理。
1.1 创建Handler
Handler有多个重载的构造方法,最终会调用到这个:
#Handler
public Handler(@Nullable Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
//判断是否写法容易导致内存泄露,默认FIND_POTENTIAL_LEAKS为false
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());
}
}
//1.获取looper
mLooper = Looper.myLooper();
if (mLooper == null) {
//1.1 如果mLooper为空,就抛出异常
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
//2. 获取消息队列
mQueue = mLooper.mQueue;
//3. 回调处理,这个在dispatchMessage时会用到
mCallback = callback;
//4. 是否是异步消息
mAsynchronous = async;
}
可以看到,里边拿到了当前线程的Looper,根据looper拿到了MessageQueue。
# Looper
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
上边代码注释中,mLooper为空,就会抛出异常,其实就从sThreadLocal.get()返回了null.
关于ThreadLocal
#ThreadLocal
public T get() {
Thread t = Thread.currentThread();
//1.获取当前线程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
//2.找到则直接返回
T result = (T)e.value;
return result;
}
}
//3. 如果map为null,或者没找到对应的T,就先设置初始值
return setInitialValue();
}
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
*
* @return the initial value
*/
private T setInitialValue() {
//默认是null
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);//创建Map
return value;
}
protected T initialValue() {
return null;
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
//创建map,并把它赋值给Thread的threaLocals变量
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
# Thread
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
每个Thread的都有一个ThreadLocalMap变量,存储的是Key-Value键值对,key是ThreadLocal,value是Thread独享的具体的变量值。当调用某个ThreadLocal的set或get方法时,会先判断这个当前执行的Thread的
threadLocals变量是否为空,如果这个map为空,则先创建一个map;调用threadlocal.set(t),如果map为空,会直接将这个传入的t作为map的初始值;threadlocal.get(),如果map空,则创建好map后,对应的value默认为null。
ThreadLocal对象是静态的,如果是非静态的,会重复创建对象TSO(thread specific object,即与线程相关的变量),
ThreadLocal与线程之间的关系,如下图所示
flowchart LR
ThreadLocal --> Thread1-->ThreadLocalMap1
ThreadLocal --> Thread2-->ThreadLocalMap2
looper对象是当前线程的线程局部变量,通过ThreadLocal保存中线程的ThreadLocalMap中。查看Looper的sThreadLocal静态变量,可以发现其是在Looper. prepare(boolean quitAllowed)方法中调用set()方法的。
其代码如下:
# Looper
private Looper(boolean quitAllowed) {
//1.初始化消息队列
mQueue = new MessageQueue(quitAllowed);
//2.获取当前线程
mThread = Thread.currentThread();
}
private static void prepare(boolean quitAllowed) {
//prepare方法不能重复调用,否则会初始化多个Looper,启动多个循环
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
后面再专门分析Looper。
1.2 Message
Message承载了线程间通信的数据,主要包含以下属性:
# Message
public int what;//主要区分消息类型
public int arg1;
public int arg2;
public Object obj;
这些是平时开发用的最多的,如果还有复杂的数据,可以使用setData()方法设置。
# Message
public void setData(Bundle data) {
this.data = data;
}
得到一个Message,除了直接new以外,最佳实践是通过一系列的obtain()方法,从消息池中获取
# Message
public static final Object sPoolSync = new Object();
//所有线程共享一个消息池,大小是50
private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
sPool一个静态变量,意味这个消息池是所有线程共享的。当消息执行完毕后,会调用message.recycle()方法,如果sPool未满,发出的消息会进入sPool中缓存起来。
Message还有几个包访问级别的属性,
//是一个状态机,32位中最后两位,分别标识正在使用和异步消息
/*package*/ int flags;
//消息最终中哪里处理,looper中获取到消息后,会调用target的dispatchMessage()方法,最终分发这个消息
/*package*/ Handler target;
// 消息的回调,handler的dispatchMessage中会优先调用消息本省的callback
/*package*/ Runnable callback;
// Message可以组成单链表,这个next指向下一个消息,MessageQueue中的消息队列和sPool缓存池,都是靠这个next指针串在一起组成链表。
/*package*/ Message next;
Message中有个setAsynchronous()方法,用来设置异步消息,Message消息可以分为3大类:
- 同步消息:使用的最多,我们一般都是发的同步消息。
- 异步消息:调用setAsynchronous(true)后将变为异步消息,这个一般和同步屏障一起使用;Handler的构造函数中有个async参数,如设为true,那通过这个handler发出的消息最终都会被设为异步消息;相对同步消息来说,是无序的,但异步消息之间是有序;如果消息之间但次序很重要,则需要慎重混用同步和异步消息。
- 同步屏障(synchronization barrier): 最大的特点是没有target,通过调用MessageQueue的postSyncBarrier(when)方法,在当前的消息队列中插入一个同步屏障,通过调用MessageQueue的removeSyncBarrier(token)移除,这两个方法都是App无法直接调用的,如果需要调用,只能通过反射去做;它的作用是,当取消的时候,如果碰到的同步屏障(即target==null的消息),对延缓队列中本该顺序执行的同步消息,找到屏障之后的异步消息来优先执行,也就是说,碰到内存屏障后,该屏障之后的所有异步消息优先于同步消息执行,直到该屏障移除。(ViewRootImpl中的scheduleTraversals和unscheduleTraversals方法中分别调用了添加和移除来同步屏障)
1.3 发送消息
handler.sendMessage()方法经过层层调用后,最终执行如下方法:
public boolean sendMessageAtTime(@NonNull 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);
}
注意里边uptimeMillis是从开机启动后去掉sleeptime的时间,是一个时间点。
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
1.4 处理消息
Handler的handleMessage方法是在dispatchMessage()方法中调用的
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
//1.先调用msg自带的callback
handleCallback(msg);
} else {
if (mCallback != null) {
//2.再调用Handler构造函数中的传递的CallBack
if (mCallback.handleMessage(msg)) {
return;
}
}
//3.最后调用Handler自身的handlerMessage方法
handleMessage(msg);
}
}
2. 整体架构
flowchart LR
subgraph MessageQueue
Message5-->Message4
Message4-->Message3
Message3-->Message2
Message2-->Message1
end
subgraph Looper
Loop((无限循环))
end
Handler --Message入队--> MessageQueue
MessageQueue --无消息阻塞有消息返回--> Looper
Looper --通知处理消息--> Handler
Handler发的消息,会进入MessageQueue中,Looper轮训从MessageQueue中取出消息,并交给Handler处理。
2.1 Looper
一个线程里边,要正常使用Handler:
- 首先要初始化Looper,即调用Looper.prepare() 方法,否则new Handler()就会抛异常;
- 要启动loop循环,即调用Looper.loop(),之后消息队列才动起来
看两个系统使用的例子,一个是ActivityThead里边,一个是HandlerThread里边
#ActivityThead
public static void main(String[] args) {
......
//1. 初始化主线程的looper
Looper.prepareMainLooper();
......
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
......
//2. 启动loop循环
Looper.loop();
//正常代码不能执行到这里,到这里说明loop循环异常了,直接抛出异常。
throw new RuntimeException("Main thread loop unexpectedly exited");
}
# HandlerThread
@Override
public void run() {
mTid = Process.myTid();
//1.初始化
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
//2. 启动loop循环
Looper.loop();
mTid = -1;
}
Looper.prepare(),主要是创建Looper,并将Looper放入当前线程的ThreadLocalMap中。Looper的构造函数里边又创建了MessageQueue。
# Looper
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));
}
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 Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper.prepare()和Looper.prepareMainLooper()的主要区别是主线程Looper不允许退出。
Looper.loop()方法主要用来启动消息队列
# Looper
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
@SuppressWarnings("AndroidFrameworkBinderIdentity")
public static void loop() {
//获取当前线程looper
final Looper me = myLooper();
······
for (;;) {
if (!loopOnce(me, ident, thresholdOverride)) {
return;
}
}
}
private static boolean loopOnce(final Looper me,
final long ident, final int thresholdOverride) {
//1.调用MessageQueue的next()方法获取消息,会阻塞当前线程。
Message msg = me.mQueue.next(); // might block
if (msg == null) {
//2. 获取消息为空,则退出
// No message indicates that the message queue is quitting.
return false;
}
······
try {
//3. 分发消息
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
······
} finally {
······
}
······
//4. 分发成功后,回收Message
msg.recycleUnchecked();
return true;
}
loop()最终在无限循环中调用loopOnce方法,loopOnce调用来MessageQueue的next()方法来获取消息,获取成功后,如果消息为空,则说明消息队列正在退出,如果不为空,则执行该消息对应的target(Handler)的dispatchMessage()方法分发消息,执行完成后,将当前消息回收,放入未满的消息缓存池中。
ActivityThreadd的H, ViewRootHandler, HandlerThread,AsyncTask
2.2 MesssageQueue
2.2.1 存
在1.3中,Handler发消息后最后调用的是MessageQueue的enqueueMessage(msg, uptimeMillis)
# MessageQueue
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
//1. 外部入队,target不能为空,只有同步屏障消息,才会target为null,而同步屏障,只有中MessageQueue的postSyncBarrier()方法中才会添加
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) { //2. 正在使用,则抛异常
throw new IllegalStateException(msg + " This message is already in use.");
}
if (mQuitting) {
// 3. 正在退出,则回收消息
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;
}
}
//4. 单链表插入队列中
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
//5. 调用native方法唤醒队列
nativeWake(mPtr);
}
}
return true;
}
2.2.2 取
Looper.loop()后会调用MessageQueue的next()方法
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();
}
//1.调用native队列的PollOnce
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
//2.1 处理有同步屏障的请求,取屏障后的第一个异步消息
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) {
//2.2 还没到执行时间,则计算下一个wakeup的时间间隔。
// 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 {
//2.3 找到消息,则设置正在使用,返回消息。
// 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) {
//3. 退出队列
dispose();
return null;
}
// 4. 处理idleHandler相关信息
// 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);
}
//4. 处理idleHandler相关信息
// 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;
}
}
MessageQueue对应一个Native的MessageQueue,这些native方法,等以后再汇总。
3. 探索
3.1 测试代码,替换HandlerThread中的Looper为主Looper
android系统提供的有AsyncLayoutInflater,也可以使用自己定义的HandlerThread线程,去预先初始化layout,这里会碰到的问题是,在子线程里预初始化的View如果里边用了Handler,默认应该是消息抛到主线程上,但现在会抛到异步inflate 视图的那个线程上去,导致程序错误。 可以考虑通过反射,将HandlerThread上对应的Looper,替换成MainLooper,来解决这个问题;在替换前new一个Handler1,它发消息,会发到当前线程对应的消息循环上;替换后,new一个新的Handler,这个Handler获取的Looper就是主线程的Looper了。
public void testReplaceLooper() {
Thread main = Thread.currentThread();
LogTool.i("TestHandlerThread ----> mainThread1 is :[" + formatObject(main)+"]" + main);
new TestHandlerThread("TestLooper").start();
}
private static final String formatObject(Object obj) {
return obj.getClass().getName() + "@" + Integer.toHexString(obj.hashCode());
}
static class TestHandlerThread extends HandlerThread {
public TestHandlerThread(String name) {
super(name);
}
public TestHandlerThread(String name, int priority) {
super(name, priority);
}
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
Handler handler1 = new Handler();
Looper looper1 = handler1.getLooper();
LogTool.d("TestHandlerThread ----> TestHandlerThread is :" + Thread.currentThread());
LogTool.w("TestHandlerThread",
"mainLooper is " + Looper.getMainLooper()+ "\n" +
"looper1 is " + looper1 + "," + isMainLooper(looper1));
//反射替换掉ThreadLocal中的looper
handler1.post(new Runnable() {
@Override
public void run() {
//在这里替换没有问题
// replaceLooper();
//
// Handler handler2 = new Handler();
// Looper looper2 = handler2.getLooper();
// LogTool.w("TestHandlerThread","looper2 is " + looper2 + "," + isMainLooper(looper2) + "\n"
// +"thread Looper is " + getLooper());
}
});
//这样替换后,主进程会崩溃;
//因为在onLooperPrepared后,调用Looper.loop()后,又启动了一个无线循环,相当于主进//程绑定的MessageQueue,有两个线程,两个无限循环在消费里边的Message,如果分发到非//主线程中的消息是UI事件,就会触发主线程的checkThread检测,提示异常
replaceLooper();
Handler handler2 = new Handler();
Looper looper2 = handler2.getLooper();
LogTool.w("TestHandlerThread","looper2 is " + looper2 + "," + isMainLooper(looper2) + "\n"
+"thread Looper is " + getLooper());
for (int i = 0;i<100;i++) {
final int index = i;
handler2.post(new Runnable() {
@Override
public void run() {
Thread main = Thread.currentThread();
//这里输出的日志,一会在主线程中打印,一会在TestHandlerThread线程中打印
LogTool.w("TestHandlerThread",index +" mainThread1 is :[" + formatObject(main)+"]"
+ main);
// +"thread Looper is " + getLooper());
}
});
}
}
private void replaceLooper() {
try {
Field sThreadLocal = Looper.class.getDeclaredField("sThreadLocal");
sThreadLocal.setAccessible(true);
ThreadLocal<Looper> threadLocal = (ThreadLocal) sThreadLocal.get(null);
Looper looper = threadLocal.get();
runOnUiThread(new Runnable() {
@Override
public void run() {
Thread main = Thread.currentThread();
LogTool.i("TestHandlerThread ----> mainThread2 is :[" + formatObject(main)+"]" + main);
}
});
LogTool.w("TestHandlerThread","replaceLooper orinial looper is " + looper +
" ,cuurentThread is = " + Thread.currentThread());
threadLocal.set(Looper.getMainLooper());
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
private boolean isMainLooper(Looper looper) {
return Looper.getMainLooper() == looper;
}
}