从源码角度分析 — Handler原理

在分析消息机制Handler之前,我们先了解下ThreadLocal这个类,ThreadLocal是一个线程内存的数据存储类。它的作用是为变量在每个线程中存储了一个副本,反过来说就是:为使用该变量的线程提供了独立的变量副本。参考一段示例代码:

private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    private void test() {
        threadLocal.set(0);
        System.out.println(Thread.currentThread().getName() + " : " + threadLocal.get());
        new FirstThread().start();
        new SecondThread().start();
    }

    class FirstThread extends Thread {

        @Override
        public void run() {
            super.run();
            threadLocal.set(1);
            System.out.println(Thread.currentThread().getName() + " : " + threadLocal.get());
        }
    }

    class SecondThread extends Thread {
        @Override
        public void run() {
            super.run();
            System.out.println(Thread.currentThread().getName() + " : " + threadLocal.get());
        }
    }

输出结果:

main : 0
Thread-0 : 1
Thread-1 : null

Process finished with exit code 0

从结果中可以发现,在主线程和工作线程FirstThread中分别设置了0和1,输出也正确。而SecondThread输出是null,使用的明明是同一个threadLocal实例,按正常推理的话应该是1才对。这是就应证了之前说那句话。下面从源码的角度去分析下,为什么会出现这样的结果。先看下set方法:

  public void set(T value) {
         //获取当前所在的线程
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        //如果不存在,则创建一个新的ThreadLocalMap
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

 void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

在上面的代码中ThreadLocalMap是ThreadLocal类中的一个静态内部类。首先,会获取ThreadLocal当前所在的线程,然后getMap()获取一个ThreadLocalMap实例,再判断是否为null。主要看下 map.set()做了什么(主要注意下注释部分):

 private void set(ThreadLocal<?> key, Object value) {
             //Entry是ThreadLocalMap的静态内部类,继承了 WeakReference<ThreadLocal<?>>
             //创建ThreadLocalMap时会同时table
            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }
            //线程对象作为key,变量副本作为value
            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

接着看ThreadLocal的get()方法

 public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        //判断当前线程map是否存在
        if (map != null) {
            //在Entry数组中查找
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) { 
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();//初始化
    }

 private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

protected T initialValue() {
        return null;
    }

从set和get中,其实可以看成是为每个线程都创建了一个ThreadLocalMap ,然后再保存需要保存的变量,这就是为什么SecondThread 获取的值为null的原因了,对于ThreadLocal其实还有很多细节方面需要注意的,但今天的主题是Handler,所以ThreadLocal先了解到这。分析前提供一张简略图:
这里写图片描述

1、上图是Handler、MessageQueue、Looper三者间大概的交互过程,首先从sendMessage()这个方法作为入口,一起看下源码:
public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

//第二个参数是延时处理时间
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);
    }

上面的代码流程也比较简单,最终会调用MessageQueue的enqueueMessage()方法,该方法也是向MessageQueue中插入Message的主要实现。接着看enqueueMessage()的源码实现:

boolean enqueueMessage(Message msg, long when) {
        //这个target是Message中的Handler的对象
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        //判断当前message是否已经使用
        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 {
                // 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 (;;) { //1
                    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;
    }

从上面代码注释1发现,向MessageQueue插入消息时,其实是以链表的形式添加消息。消息的插入就到这里,当然,发送消息的方法还有很多种,但是最终都会调用MessageQueue中的enqueueMessage()方法,这里就不在一一说明了。

2、从MessageQueue中取出消息,Looper.loop() 源码如下:
public static void loop() {
        final Looper me = myLooper();
        //1
        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 (;;) {
            //2
            Message msg = queue.next(); // might block
            if (msg == null) {
                return;
            }


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

//sThreadLocal就是我们开头讲的ThreadLocal的实例
public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

从上面的代码可以发现,在进入loop时,先通过myLooper()中的sThreadLocal获取一个Looper对象,那么这个Looper对象是什么时候保存到sThreadLocal中的呢?这个在Activity启动流程中可以找到答案,在Activity启动时有一个主要的类ActivityThread,在其入口函数main()中初始化了主线程中的Looper并且启动了loop()循环,后面会给出代码,继续跟踪上面的代码。在注释2中,queue.next()就是从MessageQueue中取出消息,在注释3通过msg.target.dispatchMessage(msg)把获取的消息进行分发。msg.target在第1步骤中已经有了说明,就是一个Handler实例对象,也就是说最终消息的分发调了Handler的dispatchMessage()方法。

3、进入MessageQueue#next()方法中:
Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        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;
                }

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

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            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);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

从上面的代码可以发现,在有新的消息到来时,就会返回这条刚到的消息,然后把消息从链表中移除,若没有消息时,则处于阻塞状态。

4、进入Handler的dispatchMessage()方法
 public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

最后调用了handleMessage,msg.callback其实是我们在new Handler().post()的时候回调的。最后看下ActivityThread中main()的源码对Looper的初始化

 public static void main(String[] args) {
        //...
        //创建主线程的Looper
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        //启动循环,且是死循环,从下面一句话可以看出
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

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

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

总结:
1、在使用new Handler()时,需要先初始化一个Looper,否则会报RuntimeException,这点文中没有贴出源码,可以自寻Handler源码。
2、创建Looper对象的同时也创建了MessageQueue对象。
3、Handler发送消息是调用MessageQueue的enqueueMessage()插入一条信息到MessageQueue中。
4、Looper#loop()会不断轮询MessageQueue的next()。
5、当获取消息后,通过调用Handler的dispatchMessage()进行消息处理。

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jack_Li_ng/article/details/79964121
个人分类: android点滴
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭