美文网首页
MessageQueue

MessageQueue

作者: Qi0907 | 来源:发表于2017-05-10 17:33 被阅读0次

    MessageQueue
    MessageQueue里面维护的只有一个Message,因为Message本身就能构建一个Message链。MessageQueue主要功能就是维护这个Message链,如插入和删除Message链中的元素,并提供获取Message链中next Message的方法
    下面就先看一下Message,Message不是一个只包含数据的类,而是一个链式结构的类,一个Message本身就是一个消息队列,它通过next将所有消息串联起来。
    简单看一下Message的几个成员变量

        /*package*/ Message next;
        private static final Object sPoolSync = new Object();// 用于访问mPool时进行同步操作
        private static Message sPool;// 全局的消息池
        private static int sPoolSize = 0;// 消息池当前大小
        private static final int MAX_POOL_SIZE = 50;// 消息池上限值
    

    一个Message本身就代表着一群Message,通过next把一系列Message给串联起来。对于无数个message实体来说,他们共享同一个全局的消息池sPool,里面存放message,并且规定了消息池的大小。

    在消息循环时,看到Loop.loop里通过循环取出消息

    public static void loop() {
            final Looper me = myLooper();
            if (me == null) {
                throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
            }
            final MessageQueue queue = me.mQueue;//拿到该looper实例中的mQueue(消息队列)
           ...
            for (;;) {//无限循环
                //取出一条消息,如果没有消息则阻塞
                Message msg = queue.next(); // might block
               ...
           //把消息交给msg的target的dispatchMessage方法去处理
                msg.target.dispatchMessage(msg);
                msg.recycleUnchecked();//释放消息占据的资源
            }
        }
    

    就看看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;
            }
    
            //为-1时,说明是第一次循环,在当前没有消息队列中没有MSG的情况下,需要处理注册的Handler
            int pendingIdleHandlerCount = -1; // -1 only during first iteration
            // 超时时间。即等待xxx毫秒后,该函数返回。如果值为0,则无须等待立即返回。如果为-1,则进入无限等待,直到有事件发生为止
            int nextPollTimeoutMillis = 0;
            for (;;) {
                if (nextPollTimeoutMillis != 0) {//???
                    Binder.flushPendingCommands();
                }
    
                // 该函数提供阻塞操作。如果nextPollTimeoutMillis为0,则该函数无须等待,立即返回。
                //如果为-1,则进入无限等待,直到有事件发生为止。
                //在第一次时,由于nextPollTimeoutMillis被初始化为0,所以该函数会立即返回
                //从消息链的头部获取消息
                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) {//message不为空,但没有执行者
                        // Stalled by a barrier.  Find the next asynchronous message in the queue.
                        do {//寻找Asynchronous的消息
                            prevMsg = msg;
                            msg = msg.next;
                        } while (msg != null && !msg.isAsynchronous());
                    }
                    if (msg != null) {
                        if (now < msg.when) {
                            //判断头节点所代表的message执行的时间是否小于当前时间
                            //如果小于,让loop()函数执行message分发过程。否则,需要让线程再次等待(when–now)毫秒
                            // 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;//将队列设置为非 blocked 状态
                            if (prevMsg != null) {
                                prevMsg.next = msg.next;
                            } else {
                                mMessages = msg.next;
                            }
                            msg.next = null;
                            if (false) Log.v("MessageQueue", "Returning message: " + msg);
                            msg.markInUse(); //将消息设置为 inuse
                            return msg;
                        }
                    } else {
                    //如果头节点为空,消息链中无消息,设置nextPollTimeoutMillis为-1,让线程阻塞住,
                    //直到有消息投递(调用enqueueMessage方法),并利用nativeWake方法解除阻塞
                        // 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)) {
                        //第一次进入,当前无消息,或还需要等待一段时间消息才能分发,获得idle handler的数量
                        pendingIdleHandlerCount = mIdleHandlers.size();
                    }
                    if (pendingIdleHandlerCount <= 0) {
                        //如果没有idle handler需要执行,阻塞线程进入下次循环
                        // 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("MessageQueue", "IdleHandler threw exception", t);
                    }
    
                    //如果keep=false,表明此idler只执行一次,把它从列表中删除。如果返回true,则表示下次空闲时,会再次执行
                    if (!keep) {
                        synchronized (this) {
                            mIdleHandlers.remove(idler);
                        }
                    }
                }
            
                //pendingIdleHandlerCount=0,是为了避免第二次循环时,再一次通知listeners
                //如果想剩余的listeners再次被调用,只有等到下一次调用next()函数了
                // Reset the idle handler count to 0 so we do not run them again.
                pendingIdleHandlerCount = 0;
    
                // nextPollTimeoutMillis=0,是为了避免在循环执行idler.queueIdle()时,有消息投递。
                //所以nextPollTimeoutMillis=0后,第二次循环在执行nativePollOnce时,会立即返回
                //如果消息链中还是没有消息,那么将会在continue;处执行完第二次循环,进行第三次循环,然后进入无限等待状态
                // 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;
            }
        }
    

    next()函数主要有三个作用:
    如果消息链中有合适的消息,就抛出message去处理。
    如果没有,通过nativePollOnce进行消息阻塞。
    在阻塞前,会通过用户注册的IdleHandler接口通知用户,线程即将处于block状态,用户可以处理一些其它的事情

    总结:
    这里的for(;;)看上去是个死循环,但实际上,每调用一次next()函数,这个循环最多只会被执行三次。
    第一次循环,如果消息链中有合适的消息,就抛出message去处理。
    如果没有,则会通知各listeners,线程空闲了。执行完后,为了避免在listners执行的过程中,有消息投递,那么此时重置nextPollTimeoutMillis,然后进行第二次循环,由于此时nextPollTimeoutMillis为0,则nativePollOnce不会阻塞,立即返回,取出message,如果此时消息链中还是没有message,则会在将会在continue处结束第二次循环,此时nextPollTimeoutMillis已被设置为-1,
    第三次循环时,nativePollOnce发现nextPollTimeoutMillis为-1,则进入无限等待状态,直到有新的message被投递到队列中来。当有新的message后,由于enqueueMessage中调用了nativeWake函数,nativePollOnce会从等待中恢复回来并返回,继续执行,然后将新的message抛出处理,for循环结束。三次循环结束。

    再看看enqueueMessage函数,该函数的目的就是把指定的Message按照绝对时间插入到当前的消息队列中去,他是在发送消息sendMessageAtTime时被调用的。

    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
            ...
            return enqueueMessage(queue, msg, uptimeMillis);
        }
    
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        ...
            return queue.enqueueMessage(msg, uptimeMillis);//保存到消息队列中
        }
    

    MessageQueue中enqueueMessage是如何实现的

        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("MessageQueue", e.getMessage(), e);
                    msg.recycle();//把这个消息放回到消息池中
                    //获得msg时,先去消息池中看看有没有被回收的msg,如果有,就不用创建新的msg了
                    return false;
                }
    
                msg.markInUse();
                msg.when = when;//从消息队列中取出绝对时间戳
                Message p = mMessages;//指向队首
                boolean needWake;
                //如果当前的消息链为空,或者要插入的MSG为QUIT消息,或者要插入的MSG时间小于消息链的第一个消息
                //在队首插入
                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 {
                    //否则,我们需要遍历该消息链,将该MSG插入到合适的位置
                    // 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;
                }
    
    //neekWake=mBlocked, 如果mBlocked为ture,表面当前线程处于阻塞状态,即nativePollOnce处于阻塞状态
    //当通过enqueueMessage插入消息后,就要把状态改为非阻塞状态,所以通过执行nativeWake方法,触发nativePollOnce函数结束等待
                // We can assume mPtr != 0 because mQuitting is false.
                if (needWake) {
                    nativeWake(mPtr);
                }
            }
            return true;
        }
    

    最后看一下移除消息,移除消息有3种,所传参数不太一样,但内部运作基本一样

    void removeMessages(Handler h, int what, Object object) {
            if (h == null) {
                return;
            }
    
            synchronized (this) {
                Message p = mMessages;
    
                // Remove all messages at front.
                //队首就匹配上了,就从队首开始删除,之后检查下一个元素是否匹配
                while (p != null && p.target == h && p.what == what
                       && (object == null || p.obj == object)) {
                    Message n = p.next;
                    mMessages = n;
                    p.recycleUnchecked();//把此msg放回到消息池中
                    p = n;
                }
    
                // Remove all messages after front.
                //查找到一个不匹配的元素,就从这个元素后面开始查找
                while (p != null) {
                    Message n = p.next;
                    if (n != null) {
                        if (n.target == h && n.what == what
                            && (object == null || n.obj == object)) {
                            Message nn = n.next;
                            n.recycleUnchecked();
                            p.next = nn;
                            continue;
                        }
                    }
                    p = n;
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:MessageQueue

          本文链接:https://www.haomeiwen.com/subject/ovugtxtx.html