Android多线程编程之Handler篇(消息机制)

Android的消息机制主要是指Handler的运行机制,Handler的运行需要底层的MessageQueue和Looper的支撑。

  • MessageQueue

消息队列,以队列的形式(实为单链表结构)对外提供插入和删除的工作,

  • Looper

以无限循环的形式不断获取MessageQueue中的消息,有则处理,无则等待。

  • ThreadLocal

ThreadLocal可以在不同的线程互不干扰的存储并提供数据,通过ThreadLocal可以很方便的获取每个线程的Looper

为什么要异步访问UI?

Android规定UI操作只能在主线程中执行,子线程执行UI操作则会抛出异常,在ViewRootImpl有如下方法:

void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

显然对于UI这类耗时操作我们不可能全部放在主线程中执行,那么就要采用异步的方式。

系统为何不允许在子线程去访问UI?

原因很简单,Android的UI线程是线程不安全的

为什么不采用加锁的方式处理UI线程?
- 会增加UI访问的逻辑复杂度
- 降低UI访问效率

至此,我们对异步消息的处理机制和必要性有了一个简单的了解

异步处理的五种基本方式

假设有如下需求:在子线程中更新TextView的文本显示

实现方式一:

mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    tv.setText(msg.obj.toString());
                }
            }
        };

        tv = (TextView) findViewById(R.id.tv);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 1;
                msg.obj = "神荼";
                mHandler.sendMessage(msg);
            }
        }).start();

实现方式二:

mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                tv.setText("神荼");
            }
        });

实现方式三:

runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv.setText("神荼");
            }
        });

实现方式四:

tv.post(new Runnable() {
            @Override
            public void run() {
                tv.setText("神荼");
            }
        });

实现方式五:

开启加速,Google异步处理方案之AsyncTask(详情请关注我的下一篇Android多线程编程之AsyncTask篇)

上述代码都实现了同样的处理效果,但实现上却略有不同,预知详细原理,请跟进代码分析。

首先来看一下Handler的工作流程:

android 线程的的sleep android线程机制_Handler

这个图清晰明白的展示出了handler异步消息处理的整个流程,我想各位看懂这个应该都是没问题,为了搞清楚内部的实现原理,我们就从handle发送消息的起点谈起,,

MessageQueue

在第一种方式中,我们通过handle.sendMessage()方法发送一个Message对象,这个msg对象的第一站即MessageQueue,MessageQueue主要包含两个操作:插入(enqueueMessage)和读取(next)

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) {
                // New head, wake up the event queue if blocked.
                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;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

上面的代码明显暴漏了这货维护的就是一个链表结构啊有木有,当该方法被调用时会向消息链表中插入新的消息对象。

再来看看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) {
                // 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;
                }


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

嗯,210-237行淋漓尽致的展现了msg是如何被取出并从链表中溢出的,没啥好说的,

Looper

我以前一直困惑Looper到底是个啥?是个类?还是个final类,不过这好像没啥意义啊…其实我们完全没必要知道它是啥,我们只要知道它对Handler形式的异步处理具有决定性的作用,实际上我们在创建Handler的时候必须伴随着两个方法的调用

  • Looper.prepare()

这里假设你已经了解ThreadLocal这货是干啥的了,基于此来看一下该方法的源码

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,那么通过本地sThreadLocal获取即可,否则新建一个,重点来了

Looper对象所“绑定”的线程也就是我们消息接收的线程

所以,你现在知道了,Looper.prepare()获取与所在线程对应的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;

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

            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);

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

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

这个玩的就更嗨了,先是获取MessageQueue对象,而后开启了自我轮回模式(无限循环),怎么轮回呢?看326行,从MessageQueue中不断地取出msg对象,然后将该msg对象分发传递出去(338),msg.target即为我们的handler对象,请注意,前方高能Handler源码解析开始…

Handler

接上面的msg.target.dispatchMessage(msg)该方法源码如下

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

看到没,该方法首先会判断callback接口,若非空,直接处理即可,这也恰恰对应了我们的第二种异步实现方式(简单来说就是直接传递一个Runnable,该Runnable最后会在Looper线程运行),那么第三种方式呢,也很类似不是么?看代码

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

看到某,就是第二种方式的封装版,而且省去了Handler的创建。

你可能要问了,mCallback是哪里冒出来野生奥特曼,干啥玩意的?

对应这个问题,我只能说,看代码

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的构造方法(不止一个),408行已然说明一切,最后我们看到在dispatchMessage终究要执行终极方法handleMessage(msg),于是乎消息对象来到了我们早已写好的handleMessage()方法中并在你Looper“绑定”的线程执行(一般都是主线程啦啦啦)…

必须要补充的点之ThreadLocal

ThreadLocal是一个线程内部的数据存储类,通过该类可以在指定的线程中存储数据,当然也只能获取当前线程的存储数据

在Handler异步消息处理中我们每个线程都要指定自己的Looper对象,那么如果没有该类,我们可能需要较为麻烦的方式去管理这些Looper对象,如hash表存储等

一个简单的使用示例

private ThreadLocal<Integer> mIntegerThreadLocal = new ThreadLocal<>();

        mIntegerThreadLocal.set(111);

        new Thread("Thread_1") {
            @Override
            public void run() {
                mIntegerThreadLocal.set(222);
                Log.d("TAG2", mIntegerThreadLocal.get().toString());
                Log.d("TAG", Thread.currentThread().getName());
            }
        }.start();

        new Thread("Thread_2") {
            @Override
            public void run() {
                mIntegerThreadLocal.set(333);
                Log.d("TAG3", mIntegerThreadLocal.get().toString());
                Log.d("TAG", Thread.currentThread().getName());
            }
        }.start();

        Log.d("TAG1", mIntegerThreadLocal.get().toString());
        Log.d("TAG", Thread.currentThread().getName());

输出:

android 线程的的sleep android线程机制_Message_02

显然,结果表明了同一个对象在不同的线程有着不同的值,再来看一下它内部的源码实现(以搞懂源码为目标)

首先是set方法

public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }

看到某,ThreadLocal能根据不同线程维护不同Values对象(Thread内部产生),进而存储获取不同的数据,更具体的可以自行查阅源码。

再来看下get

public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }

和set类似,清楚明白不扯淡,就不多说了

必须要补充的点之主线程消息循环

聊了这么久,有人可能就问了,你说使用handler必须要调用Looper的prepare和loop方法,那么主线程(ActivityThread)并没有看到调用啊,你净扯犊子呢?
有此问的道友先息息火,关于这个问题其实很简单,Android已经为我们做好了封装,而且第一个方法调用的是Looper.prepareMainLooper()

public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

OK,到此为止我相信你应该是彻底搞懂了了Handler的异步消息机制,如果还有什么疑问欢迎下方留言,当然我建议你能抽点时间自己去一点点的去阅读分析handler的源码,这样才能真正深刻的理解并记忆。