Android MessageQueue 底层实现(java)

一、如何使用消息队列

使用消息队列需要准备如下三个类:

类名功能
Handler负责发送和接收消息
Looper负责从消息队列取消息,然后派发消息
Message用于承载消息

要理解消息队列的底层工作原理,首先要知道怎么在程序中使用消息队列。由于消息队列是 Android 系统的功能,所以必须在 Android SDK 环境编写测试程序。故在 Activity 中创建一个线程作为测试程序的主线线程,具体代码如下:

package com.huangchao.messagequeuetest;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MessageQueueTest";
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @SuppressLint("HandlerLeak")
            @Override
            public void run() {
                final Bank bank = new Bank(1000);
                Looper.prepare();

                handler = new Handler() {
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        super.handleMessage(msg);
                        if (msg.what == WITHDRAWMONEY) {
                            bank.withdrawMoney(100);
                        }
                    }
                };

                for (int i = 0; i < 10; i++) {
                    Thread thread = new Thread(new Customer(handler));
                    thread.start();
                }

                Looper.loop();
            }
        }).start();
    }

    private static final int WITHDRAWMONEY = 0;

    static class Bank {
        private int account;

        Bank(int count) {
            account = count;
        }

        public void withdrawMoney(int num) {
            //account -= num;
            int local_account = account;
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            local_account -= num;
            account = local_account;
            Log.d(TAG, Thread.currentThread().getName() + "-> 取款:" + num + ", 余额:" + account);
        }
    }

    static class Customer implements Runnable {
        Handler handler;

        public Customer(Handler handler) {
            this.handler = handler;
        }

        public void run() {
            //Message message = handler.obtainMessage();
            handler.sendEmptyMessage(WITHDRAWMONEY);
        }
    }
}

从上面的程序,可以总结消息队列的一般使用步骤:

  1. 主线程通过 Looper.prepare() 创建 Looper;
  2. 在主线程定义 Handler;
  3. 主线程调用 Looper.loop(); 进入事件循环;
  4. 子线程通过 handler.sendEmptyMessage 发送消息;
  5. handler 回调 handleMessage 处理消息。

上面的测试程序存在以下疑问:

  1. 为什么不在 MainActivity 主线程中进行事件循环?
  2. handleMessage 函数数是在哪个线程执行?

要解决上面的问题则需要深入的研究消息队列的设计原理。

二、消息队列的工作原理

下面根据测试程序的流程逐步分析底层实现。

2.1 首先是创建 Looper

[Looper.java->prepare()]

    public static void prepare() {
        prepare(true);
    }
    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

从上面代码可知 Looper 设计类似于单例模式,但于单例不同是,每一个线程只允许一个 Looper 实例,sThreadLocal 是 ThreadLocal 类型,它是 TLS 变量,实现线程内部全局访问。

2.2 创建 Handler

Handler 构造函数如下:
[Handler.java->Handler(Looper looper, Callback callback, boolean async) ]

    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

Handler 从字面来看就是一个句柄,那么它应该是内部持有某个对象。果然构造函数中通过 mQueue 引用了 Looper 管理的消息队列,所以 Handler 持有的与 Looper 关联的消息队列。
因为 Looper 是线程关联的,而 Hanler 与 Looper 又是关联的,所以要求 Handler 和 Looper 必须定义在同一个线程,并且需要先定义 Looper 在定义 Handler。

2.3 Looper 进入消息循环

通过静态函数 loop() 进入消息循环
[Looper.java -> 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;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            // This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);    // 处理消息
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // identity of the thread wasn't corrupted.
            final long newIdent = Binder.clearCallingIdentity();
            if (ident != newIdent) {
                Log.wtf(TAG, "Thread identity changed from 0x"
                        + Long.toHexString(ident) + " to 0x"
                        + Long.toHexString(newIdent) + " while dispatching to "
                        + msg.target.getClass().getName() + " "
                        + msg.callback + " what=" + msg.what);
            }

            msg.recycleUnchecked();
        }
    }

首先调用 myLooper 获取本线程的 Looper 实例,然后从 Looper 中取出消息队列 me.mQueue,最后调用消息队列的 next() 函数取消息,如果消息队列为空则阻塞当前进程,如果有消息需要处理则调用 msg.target.dispatchMessage(msg); 处理消息。
那么 mQueue 成员变量在哪里初始化呢?答案是 Looper 的构造函数:
[Looper.java -> Looper(boolean quitAllowed)]

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

可见每一个 Looper 都会关联一个 MessageQueue。接着分析 MessageQueue 的 next() 函数:
[MessageQueue.java -> next()]

   Message next() {
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis); // 阻塞,直到下一个消息需要处理,或者有新消息入队

            synchronized (this) {
                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 {
                    // 消息队列为空,下次执行 nativePollOnce 阻塞直到有消息入队
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // 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);
            }

            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(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            pendingIdleHandlerCount = 0;
            nextPollTimeoutMillis = 0;
        }
    }

首先调用 nativePollOnce 进入阻塞,阻塞时间为 nextPollTimeoutMillis,该时间为下一个消息的就绪时间,如果期间有消息入队,则会提前结束阻塞。nativePollOnce 是一个 native 函数,底层通过 epoll 多路复用接口,同时处理 native 层和 java 层的消息循环。具体实现后续再分析。注意第一次调用 nativePollOnce,nextPollTimeoutMillis 设置为 0,即不阻塞。
nativePollOnce 返回后,从消息队列中取出第一个消息。首先判断当前是否为屏障消息,如果是屏障消息,则找到下一个异步消息进行后续处理,否则就处理当前消息。
如果待处理消息为空,则说明 cpu 处于空闲状态,将处理 mIdleHandlers 中的任务,并设置下一次 nativePollOnce 永久阻塞。
如果待处理消息非空,比较消息的 when 参数与当前时间,判断消息是否就绪。如果 when 比当前时间后,说明消息未就绪,则计算它们的差值作为下一次 nativePollOnce 的阻塞时间。期间也会处理mIdleHandlers 中的任务。 如果 when 比当前时间前,说明消息已经就绪,则返回,由 Looper 对象消息进行分发。

相关数据结构说明:
mMessages 消息队列头指针,它按时间顺序保存消息,最新的消息会放在队列的头部。
Message 消息类,when 域表示消息就绪时间,target 域表示消息的目标 Handler,当消息就绪时,目标 Handler 的 handleMessage 将会被调用。

2.4 Handler 发送消息

测试程序发送消息代码 :andler.sendEmptyMessage(WITHDRAWMONEY);
[Handler.java -> sendEmptyMessage(int what)]

    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }
    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }
    public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        if (queue == null) {
            RuntimeException e = new RuntimeException(
                    this + " sendMessageAtTime() called with no mQueue");
            Log.w("Looper", e.getMessage(), e);
            return false;
        }
        return enqueueMessage(queue, msg, uptimeMillis);
    }
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

通过上面的源码可知,发送一个空消息底层的步骤如下:

  1. 通过 Message 的 obtain 函数获取一个 Message 实例;
  2. 初始化消息标识 what,就绪时间 when;
  3. 调用 mQueue 的 enqueueMessage 将消息入队,并执行 target 域为 this;

消息入队的源码如下:
[MessageQueue.java -> enqueueMessage(Message msg, long when)]

    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(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // 消息队列为空,则将对新消息作为消息队列头部
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // 根据时间顺序,将消息插入到队列的合适位置
                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;
            }

            // 如果正在处理消息,则无需唤醒 loop (优化不必要的唤醒)
            if (needWake) {
                nativeWake(mPtr);   // 唤醒主线程的 loop
            }
        }
        return true;
    }

2.5 Handler 处理消息

Looper 获取到消息后,开始处理消息消息,处理消息的函数是 target 的 dispatchMessage。target 参数在消息入队时,赋值为 this,即发送的的 Handler,则 Handler 的 dispatchMessage 被调用。

msg.target.dispatchMessage(msg);

接着继续分析 dispatchMessage 函数:
[Handler.java -> dispatchMessage(Message msg)]

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

消息可能分发到三个地方,第一个是 msg 自己的 callback 对象(使用 post 发送数据时赋值);第二个是 Handler 的 mCallback 对象;第三个是 Handler 的 handleMessage 函数。即在定义 Handler 是复写的接口。三个消息受体是有优先级的,如果消息被处理则不会继续分发。
至此消息的传递流程已经完整。

回过头来看前面遗留的两个问题,现在就能解答了。
1、为什么不在 MainActivity 主线程中进行事件循环?
这是因为 Activity 主线程有自己的事件循环,如果再调用 prepare 函数则会抛出异常 “Only one Looper may be created per thread”。
2、handleMessage 函数数是在哪个线程执行?
通过上述代码分析,可知是 Looper 回调了 Handler 的 handleMessage,故 handleMessage 应该在 Looper 所在线程执行。从而实现了线程通信。

测试程序下载地址

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

翻滚吧香香

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值