Android跨线程消息机制

610 阅读10分钟

在这里插入图片描述

消息分发和处理是如何工作的?

消息处理框架如何创建和启动

1.创建消息循环分发对象Looper
    private Looper(boolean quitAllowed) {
        //消息储存的队列
        mQueue = new MessageQueue(quitAllowed);
        //创建消息处理框架的线程
        mThread = Thread.currentThread();
    }
    
    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));
    }
    
    //开启消息循环
    public static void loop() {
        final Looper me = myLooper();
        //检查当前线程是否已经创建了Looper对象并缓存
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;//当前looper需要分发的消息的消息队列
        boolean slowDeliveryDetected = false;//日志开关
        //注意:死循环遍历
        for (;;) {
            Message msg = queue.next(); // 获取下一个消息 => 可能会阻塞(比如消息队列为空时,后续分析该源码)但是阻塞会释放cpu,这是为什么死循环遍历却不会导致主线程卡住的原因
            if (msg == null) {
                //这里标示着消息分发流程已经终止了
                return;
            }

            // 获取当前日志打印服务提供者,Looper允许外部设置自己的打印服务,比如主线程就在ActivityThread中设置了LogPrinter对象,一些卡顿检测框架就是根据消息处理前后的日志中的时间来统计耗时的
            final Printer logging = me.mLogging;
            if (logging != null) {
                //打印当前消息开始分发和处理的时间
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            ...//Trace对象来跟踪处理时间
            try {
                //将消息分发给其目标处理者 => 消息不能没有目标处理者 
                msg.target.dispatchMessage(msg);//消息处理流程后续分析
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            
            if (logging != null) {
                //打印消息处理结束日志
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            //回收该消息:将该消息加入对象池 并重置其状态
            msg.recycleUnchecked();
        }
    }
  1. Looper只能通过prepare及其重载方法创建,且同一线程中只能创建一次(即调用prepare方法一次),创建后存储在ThreadLocal中
  2. Looper对象创建时必须创建MessageQueue队列,可理解为将消息分发者和消息来源(消息队列)建立联系
  3. 消息循环是死循环遍历,其不卡住的原因是消息队列的next方法虽然阻塞,但是会释放cpu
扩展:ThreadLocal的set方法是如何工作的?
    public void set(T value) {
        //获取此方法被调用时所在的线程
        Thread t = Thread.currentThread();
        //获取Thread对象的threadLocals变量 类型是ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        if (map != null)
            //将当前value保存到map中,key为当前的ThreadLocal,即:ThreadLocalMap对象可以保存多个value,但同一个ThreadLocal对象,只会有一个value被保存
            map.set(this, value);
        else
        //如果map为空 则会创建一个ThreadLocalMap对象并设置初始值
            createMap(t, value);
    }
    
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    /**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
2.创建消息处理者
    public Handler(Callback callback, boolean async) {
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

1.创建Handler对象时,将消息分发对象、消息队列等复制给处理者,这里callback在消息处理时会用到,mAsynchronous表示是否为异步,后面解释异步消息原理时用到

消息如何创建和发送给消息框架

创建一个空消息
    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 static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // 清空消息的状态
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

1.Message对象可以直接创建或者从对象缓存池中获取

发送消息给消息队列
    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        //发送一个在将来时间点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) {
        //消息的目标设置当前handler
        msg.target = this;
        if (mAsynchronous) {
            //如果handler是异步handler,则其发送的消息都是异步消息 => 异步消息在后续分析
            msg.setAsynchronous(true);
        }
        //将消息添加到消息队列
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    
    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;//mBlocked表示是否在消息分发时阻塞 =>如果之前looper在此队列上阻塞,则需要唤醒
            } 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;
            }

            //如果需要唤醒等待者,则通过native的方法唤醒,这里mPtr为native层消息队列的地址
            if (needWake) {
                //实际上,native层是通过向管道写入某个字符来唤醒管道另一端的等待者,
                nativeWake(mPtr);//这里调用后,会唤醒在MessageQueue的next方法上等待的Looper,
            }
        }
        return true;
    }

1.消息队列由链表实现,其容量无限制

消息框架如何分发和处理消息

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
  1. 如果消息自己携带了callback(Runnable类型),则直接调用callback的run方法 否则到第2步
  2. 如果Handler中mCallback不为空,则调用mCallback的handleMessage方法处理 如果其放回true,则终止后续流程
  3. 直接调用Handler自身的handleMessage方法处理消息

Handler是如何切换线程的

Handler是用于同一个进程的线程间通信。Looper让主线程无限循环地从自己的MessageQueue拿出消息处理,所以我们就可以知道处理消息肯定是在主线程中处理的,那么是怎样在其他的线程往主线程的队列里放入消息呢?道理其实很简单,我们知道在同一进程中线程和线程之间资源是共享的,也就是对于任何变量在任何线程都是可以访问和修改的,只要考虑并发性做好同步就行了,那么只要拿到MessageQueue 的实例,就可以往主线程的MessageQueue放入消息,主线程在轮询的时候就可以在主线程处理这个消息。那么是怎么拿到主线程 MessageQueue的实例呢,当然是可以拿到的(在主线程下mLooper = Looper.myLooper();mQueue = mLooper.mQueue;),Google 为了统一添加消息和消息的回调处理,又专门构建了Handler类,你只要在主线程构建Handler类,那么这个Handler实例就获取主线程MessageQueue实例的引用(获取方式mLooper = Looper.myLooper();mQueue = mLooper.mQueue;),Handler 在sendMessage的时候就通过这个引用往消息队列里插入新消息。Handler 的另外一个作用,就是能统一处理消息的回调。这样一个Handler发出消息又确保消息处理也是自己来做,这样的设计非常的赞。具体做法就是在队列里面的Message持有Handler的引用(哪个handler 把它放到队列里,message就持有了这个handler的引用),然后等到主线程轮询到这个message的时候,就来回调我们经常重写的Handler的handleMessage(Message msg)方法。

空闲消息是如何工作的?及其实际应用

    Message next() {
        final long ptr = mPtr;
        if (ptr == 0) {
            //表示消息处理已经停止
            return null;
        }

        int pendingIdleHandlerCount = -1; // 需要空闲消息数量
        int nextPollTimeoutMillis = 0;//poll消息需等待的时间 此处只有native层会使用该值,对native而言 其值有多重含义:0:直接返回 -1:无限等待 其他值:等待时常 [详情](https://www.kancloud.cn/alex_wsc/android-deep2/413394)
        //死循环遍历
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            //通知native层消费其消息,该方法会阻塞,其是当前方法阻塞的原因
            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;
                //如果头节点消息没有target 这种情况是由于给消息队列设置了异步栅栏
                if (msg != null && msg.target == null) {
                    //找到第一个异步消息,此处是为了栅栏设计
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // 下一个消息还没有准备好 所以设置一个下一次唤醒的延时时间
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        //找到了一个msg,将消息从队列中移除
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        msg.markInUse();
                        //直接返回该消息
                        return msg;
                    }
                } else {
                    // 没有更多消息 nextPollTimeoutMillis = -1时 nativePollOnce方法会无限阻塞
                    nextPollTimeoutMillis = -1;
                }

                // 正在退出
                if (mQuitting) {
                    dispose();
                    return null;
                }

                //pendingIdleHandlerCount只可能在第一次赋值时时小于0
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    /此时没有消息需要处理:即空闲状态
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // 没有需要在空闲状态下执行的任务 则标记进入阻塞状态
                    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; // 释放保存的空闲时任务数组

                boolean keep = false;//是否需要保存该任务
                try {
                    keep = idler.queueIdle();//如果这里返回了true 即保持该任务 那么该任务下次空闲时会再被执行
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }
                //如果不需要保持 则会移除该任务
                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // 重置空闲时任务数量
            pendingIdleHandlerCount = 0;

            //设置等待时间为0 防止在处理空闲任务时添加了新的任务
            nextPollTimeoutMillis = 0;
        }
    }

栅栏设计原理及其应用?

栅栏的作用:添加栅栏后,消息队列的next不会返回同步消息,只会返回异步消息。又因为消息默认时同步的,所以此时Looper线程将阻塞业务消息的分发和处理。待移除栅栏后,才会分发和处理。 栅栏的应用:ViewRootImpl请求垂直同步信号时,添加一个栅栏给主线程的队列,之后业务方post的消息都不会执行,直到处置同步回调时移除了栅栏

    public int postSyncBarrier() {
        return postSyncBarrier(SystemClock.uptimeMillis());
    }

    //向消息队列中添加一个异步栅栏 返回值为该栅栏的token  移除栅栏需要使用到token
    private int postSyncBarrier(long when) {
        //这里添加栅栏的目的是 拦住同步消息的分发和处理 所以不用去唤醒队列
        synchronized (this) {
            final int token = mNextBarrierToken++;//栅栏的token 标示栅栏唯一性
            final Message msg = Message.obtain();
            msg.markInUse();
            msg.when = when;
            msg.arg1 = token;
            //将消息添加到队列中 需要注意 这里的消息没有target 即没有处理者 如果记得文章前面的next方法的实现,就会知道栅栏是怎么拦截同步消息的
            Message prev = null;
            Message p = mMessages;
            if (when != 0) {
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
            }
            if (prev != null) { // invariant: p == prev.next
                msg.next = p;
                prev.next = msg;
            } else {
                msg.next = p;
                mMessages = msg;
            }
            return token;
        }
    }

最后附上类图

在这里插入图片描述