1.一个线程有多少个Handler
一个线程可以有无数个Handler,直接new出来就行
2.一个线程有几个Looper,如果保证?
一个线程只有一个Looper,原因是:
// 1.构造方法私有化
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
*****
// 2.prepare方法内部通过ThreadLocal来新建当前的Looper,调用prepare方法时会对ThreadLocal进行null判断,如果不为null时就说明有值了,抛出异常,确保了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));
}
3.Handler内存泄漏原因?为什么其他的内部类没有说过这个问题
非静态内部类,或者匿名内部类。默认持有外部类引用。如果MessageQueue里面还有为处理完的消息,那么Activity被销毁时就无法成功,这就导致了内存泄漏。解决的方式是将Handler的实现进行static修饰,同时传递进来的Activity进行WeakRefrence引用,在Activity的onDestory的时候清除掉所有的消息。
4.为何主线程可以new Handler?如果想在子线程new Handler需要做些什么准备?
主线程直接new Handler的源头是主线程在应用在创建的时候就会新建一个Looper,然后会调用Looper.loop(),子线程需要先调用Looper.prepare()方法,sendMessage后调用Looper.loop()进行消息的分发
5.子线程种维护的Looper,消息队列无消息的时候的处理方案是什么?有什么用?
6.既然可以存在多个Handler往MessageQueue中添加数据(发送消息时Handler可能处于不同的线程),那它内部是如何确保线程安全的?
通过下面代码可以看到这里是通过加锁来实现线程安全的
//MessageQueue.java
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;
}
...
7.我们使用Message时应该如何创建它?
Message 我们可以直接new 也可以 通过obtain 来获取复用的 message 实例。
那么这里问的就是obtain 的运作逻辑和为什么要用obtain
//Message.java
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();
}
这里用了一个享元模式,Message 是Android系统中很常见的一个类,如果我们每次使用都new的话 ,这个内存就抖动起来了呀。 这里也是为了避免过多的内存创建销毁的过程,平稳使用内存。
8.Looper死循环为什么不会导致ANR
总结起来都是 有某些地方发送了 timeout的 message ,然后hander 处理了这个message。
而当 looper 就是循环读取messagequeue的message 然后处理,如果没有message 就等待 这时候 的等待是不可能达成这个anr的逻辑的。
9.消息屏障机制是怎样的?
View进行刷新的时候,会先发送一个屏障消息,然后再刷新一个刷新屏幕的异步消息,在进行消息轮询的时候就会判断是否有屏障消息,如果有的话就拿到刷新屏幕的消息,等这个消息分发完成后就移除屏障消息,接下来就等剩下的消息继续进行
10.Handler是如何进行消息等待和唤醒的?
每次发送消息的时候首先会根据时间进行排序,然后取出第一个消息,如果检查是否达到了发送的时间,如果时间没到,就调用nativePollOnce
补充:
1.handler.sendMessage()方法最终都会执行sendMessageAtTime(Message msg, long uptimeMillis)
public boolean sendMessageAtTime(Message msg, long uptimeMillis) { // uptimeMillis = System.currentTimeMillis() + dalyTimes
....
return enqueuMessage(queue, msg, uptimeMillis);
}
//然后enqueueMessage()会调用MessageQueue的enqueueMessage()方法,在MessageQueue的enqueueMessage方法里面进行消息的排序和唤醒
2.MessageQueue里面的消息一共有三种:普通Message、SyncBarrier(屏障消息,Message的target为null)和异步消息(Message的isAsynchronous为true)。
3.每次刷新UI都需要发送三个消息:postSyncBarrier->异步消息->removeSyncBarrier,这三个消息也会遵循MessageQueue的时间排序机制,
// MessageQueue取出消息分析
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();
}
// 这里是epoll原理,保证如果消息时间未到就等待,直到被唤醒
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;
// msg.target == null的消息其实是同步屏障消息,同步屏障消息一般是成对出现的,有个开始的,也有个remove的
if (msg != null && msg.target == null) {
// Stalled by a barrier. Find the next asynchronous message in the queue.
do {
prevMsg = msg;// 这个prevMsg就变成屏障消息对象了
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;
}
}