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++;}}
}