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.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.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值