| 
                         顾名思义,MessageQueue 就是消息队列,即存放多条消息 Message 的容器,它采用的是单向链表数据结构,而非队列。它的 next()  指向链表的下一个 Message 元素。 
- boolean enqueueMessage(Message msg, long when) { 
 -  // ... 省略一些检查代码 
 -  synchronized (this) { 
 -  // ... 省略一些检查代码 
 -  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; 
 -  } 
 -  } 
 -  msg.next = p; // invariant: p == prev.next 
 -  prev.next = msg; 
 -  } 
 -  // We can assume mPtr != 0 because mQuitting is false. 
 -  if (needWake) { 
 -  nativeWake(mPtr); 
 -  } 
 -  } 
 -  return true; 
 - } 
 
  
从入队消息 enqueueMessage()  的实现来看,它的主要操作其实就是单链表的插入操作,这里就不做过多的解释了,我们可能应该更多的关心它的出队操作方法 next(): 
- Message next() { 
 -  // ... 
 -  int nextPollTimeoutMillis = 0; 
 -  for (;;) { 
 -  // ... 
 -  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 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; 
 -  } 
 -  //... 
 -  } 
 -  //... 
 -  // 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; 
 -  } 
 - } 
 
                          (编辑:52站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |