MessageQueue

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;
            }
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容