1.Message类的支持
- 使用链表来缓存Message,sPool为表头;
- 最多能缓存50个Message;
- sPoolSync用来保证读写链表的安全;
public final class Message implements Parcelable {private static Message sPool; //缓存的列表表头/*package*/ Message next;private static final Object sPoolSync = new Object();private static int sPoolSize = 0;//当前缓存的Message的个数private static final int MAX_POOL_SIZE = 50; //最多只能缓存50个Message
}
2.获得消息
- 返回表头的Message,将下一个消息更新为新的表头;
public final class Message implements Parcelable {public static Message obtain() {synchronized (sPoolSync) {//加锁,线程安全if (sPool != null) {Message m = sPool;//获得表头sPool = m.next; //更新表头m.next = null; //将返回的Message的next重置m.flags = 0; // clear in-use flagsPoolSize--; //更新缓存的Message数量return m;}}return new Message(); //不然新建一个}
}
3.缓存消息
- 在Looper里面执行消息;
- 执行完消息后,将Message缓存;
public final class Looper {public static void loop() {for (;;) {Message msg = queue.next();if (msg == null) {return;}msg.target.dispatchMessage(msg); //执行Messagemsg.recycleUnchecked(); //执行消息回收 }}
}
void recycleUnchecked() {// Mark the message as in use while it remains in the recycled object pool.// Clear out all other details.//重置所有属性flags = FLAG_IN_USE;what = 0;arg1 = 0;arg2 = 0;obj = null;replyTo = null;sendingUid = -1;when = 0;target = null;callback = null;data = null;synchronized (sPoolSync) {//加锁if (sPoolSize < MAX_POOL_SIZE) {//只能缓存50个消息next = sPool; //每次执行完消息后,放这条消息放到头部sPool = this;//更换表头sPoolSize++;}}
}