Android线程间通信基础——Handler,Looper,MessageQueue

Android单线程模型

  我们知道进程是cpu资源分配的最小单位,线程是cpu调度的最小单位。早期的操作系统里进程既是资源分配也是调度的最小单位,后来随着cpu速度越来越快,为了更合理的使用cpu,减少进程切换的开销,才将资源分配和调度分开,就有了线程。线程是建立在进程的基础上的一次程序运行单位。
  当我们第一次打开一个App时,系统就会给这个App分配一个进程,并且启动一个main thread线程,主线程主要负责处理与UI相关的事件,如:用户的按键事件,用户接触屏幕的事件以及屏幕绘图事件,并把相关的事件分发到对应的组件进行处理。所以主线程通常又被叫做UI线程。
  在开发Android 应用时必须遵守单线程模型的原则: Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行。

疑问

  既然UI操作只能在UI线程里更新,那么可不可以把所有操作都放在UI线程里面呢?答案是不可能的,可能会导致ANR。所以一些常用的耗时操作只能在非UI线程里执行,比如网络,数据库,IO操作等。那在非UI线程执行完后我们想把处理结果通知给UI线程怎么办,这就涉及到线程间通信的问题。
  传统的Java线程间通信包括volatile,synchronized,CountDownLatch等不适合于Android,因为AndroidUI线程是消息驱动模式,主线程在启动时会初始化一个Looper,并调用loop()方法开启死循环,在循环里执行处理消息的操作。

大致流程图如下:

handler_watermark.png

UML类图

uml_watermark.png

流程讲解

  接下来我们以handler的创建为起始点,结合源码开始讲解。

hander创建(UI线程中)

handler = new Handler();

查看构造函数:

public Handler() {
        this(null, false);
}

这里可以传入两个参数,一个为callback,他是Handler的内部接口,里面只有一个方法:

public interface Callback {
        /**
         * @param msg A {@link android.os.Message Message} object
         * @return True if no further handling is desired
         */
        public boolean handleMessage(Message msg);
}

也就是我们初始化Handler的时候可以传入一个Callback,之后Looper会回调这个Callback。
另一个参数表示是否是异步消息

Handler.java

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;
}

  可以看见这里面会获取Looper,如果Looper为空,则会报错;由于Handler实在主线程里面创建的,默认用的是主线程的Looper,而主线程的Looper实在ActivityThread的main方法中创建的。所以如果在其他线程创建Handler必须显示的创建Looper。

  我们进入Looper.myLooper()方法里面看看

Handler.java

static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
/**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

  ThreadLocal是一个类似于HashMap的数据结构,它主要是用于保存线程的局部变量,ThreadLocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量。
  也就是myLooper()会获取当前线程的Looper,那么主线程的Looper实在哪创建的呢?答案是在ActivityThread中

ActivityThread.java

    public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        ...
        Looper.loop();
    }

Looper.java

/**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

调用prepare方法

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));
    }

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

所以就是在这创建完Looper的,并且创建想赢的MessageQueue,然后把Looper保存到ThreadLocal中
结论:一个线程对应一个Looper对应一个MessageQueue

发送消息

   Handler创建完毕后,我们就可以发送消息了,发送消息有几种方式,如post(),sendMessage();最终都会调用handler的sendMessageAtTime()方法(post 的Runnnale也会包装成Message)

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);
}

mQueue就是在创建Handler时赋值的,它会调用MessageQueue的enqueueMessage方法

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
}

这里要注意的是把msg.target指向了自己,这是为了Looper处理完消息后回调自己的相关方法。
接下来进入MessageQueue里面

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);
            }
            ....
        }
        ....

}

  mMessages是当前Looper正在处理的消息,即消息队列的队头,赋值的地方是在next()方法里面;即如果当前队头的消息为空或者待入队的消息延时为0或者待入队的消息的延时小于队头的延时,则把待入队的消息插入到队的头部;
  这可以看出MessageQueue是一个按when顺序排列的优先级队列,队头的when是最小
  同时加入之前是延迟消息,会阻塞当前队列,所以还需要唤醒

  else里面会开启for循环,这个循环的目的是插入消息到链表的中间:如果插入消息到链表头部的条件不具备,则依次循环消息链表比较触发时间的长短,然后将消息插入到消息链表的合适位置。接着如果需要唤醒线程处理则调用C++中的nativeWake()函数。

这样handler插入消息的流程就完毕了

Looper消息循环

  当消息队列中有消息的时候,Looper就会去取出消息并执行,具体在Looper的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;
        ...
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            ...

            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
          
            ...

            

            msg.recycleUnchecked();
        }
    
}

  这里面主要就是从MessageQueue中取出Message执行,即调用queue.next(),然后handler的dispatchMessage()方法,前面提到过msg.target执行的就是我们的handler。然后回收message,可以复用;这也是为什么建议用Message.obtain()来生成message的原因。
  接下来看MessageQueue的next方法

Message next() {
        ...
        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;
                }

                // 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)) {
                    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);
            }
        }
        ...
}

  nativePollOnce(ptr, nextPollTimeoutMillis);是一个native方法,它的作用是在native层阻塞,对用nativeWake()唤醒,接下通过do while循环在MessageQueue中找message,如果Handler传入了async参数为true,这里的msg.isAsynchronous()为true,循环退出,即找出第一个不为空的同步message或者异步message;
  找到后会计算该message的执行时间是不是现在这个时间点,如果还没到它该执行的时间点,则计算剩余的时间 nextPollTimeoutMillis,否则的话该message就是我们要找的message,然后取出该message,并改变链表的指针。
  值得一提的是MessageQueue有个有趣的接口IdleHandler,看名字就知道它是个空的handler,当MessageQueue中没有消息的时候,如果有IdleHandler,则会调用queueIdle()方法,关于它的用法之后我们会讲到。

Message走了一圈又回到了Handler

Message从子线程走到了主线程,走了一圈又回到了Handler

/**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

  如果Message设置了回调方法的话,则回调该方法,这个是当我们调用handler.post(Runnable able)时设置的,即这个callback就是runnable,他会调用用runnable的run方法;
  如果Message没设置回调,并且handler设置了callback,这个callback是在构造方法里面设置的,之前讲到过,然后回调callback的handleMessage();
  如果前两步都没设置回调,则会调用自身的handleMessage(msg)方法,这个就是我们熟悉的,经常复写的方法。

总结

  终上所述,一个message从子线程走到了主线程,这其中都是Handler的功劳,handler负责发送消息入队,然后处理消息,这样完成了一个操作从子线程到主线程的切换,其本质就是把一个操作从子线程传递给主线程。关于子线程更新UI的相关有趣操作我们会在另外的文章里讲。
  Tips1: handler在哪个线程创建,持有的就是哪个线程的Looper,MessageQueue。当然你也可以在构造函数中显示的指定哪个线程的Looper。比如主线程创建的默认是主线程的mainLooper。
  Tips2: 子线程创建Handler,由于子线程没有自己的Looper,所以必须显示调用Looper.prepare()创建Looper,并且显示的调用Looper.loop()方法开启消息循环。
  Tips3: handler的底层用的是Linux的管道通信,至于原因,我们之后再讲;

Message流向图

message_watermark.png

时序图

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

推荐阅读更多精彩内容