Handler運行機制和源碼分析

Handler的用處

我們都知道Android是禁止在非主線程更新UI的,其主要原因是UI控件並不是線程安全的,如果多線程訪問UI,將會出現非常多的問題。你可能會想到使用sychronized給UI控件加鎖,但是加鎖會帶來兩個問題,一方面影響運行效率,另一方面會使得UI訪問邏輯變得很複雜。爲了避免這些問題,所以才採用了單線程更新UI的方式。那麼當我們正處於子線程時,如何能夠更新UI呢?這時就可以使用Handler來進行線程的切換了,這也是我們最常用的方法。

與Handler相關的主要成員功能

  • ThreadLocal 用於存儲不同線程中的Looper,是每一個線程,都已唯一與之對應的Looper。
  • Looper 主要用於從MessageQueue中取出消息,並交給handler處理消息。
  • MessageQueue 用於以隊列的方式存儲取出消息,實質是鏈表的形式。
  • Handler 用於發送信息以及接受信息,並對信息進行處理。
    下面我將會結合源碼對以上四個方面進行講述

ThreadLocal

TreadLocal是一個數據存儲類,數據存儲後,只有在指定的線程中才能取出存儲的數據,對於其它線程則無法獲得數據。ThreadLocal使得每一個線程中都能與當前線程相對應的數據,且每個線程對應的數據互不干擾。
我們首先來看一下它的set方法。

//ThreadLocal
public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

可以看到set方法首先會嘗試通過thread獲得TreadLocalMap類,這個類是TreadLocal的靜態內部類

static class ThreadLocalMap {
	private Entry[] table;
	static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }
}

可以看到裏面是有一個Entry數組,TreadLocal中的數據就是存在這裏的,順便一提這裏的WeakReference指的是弱引用方式,這種引用的特殊之處在於,當存儲的數據沒有強引用時,如果GC執行回收時,就會自動銷燬數據,從而防止了內存泄漏,這裏就不多說了。

然後在每一個Thread中都有着一個TreadLocalMap的成員變量,getMap方法就是獲得所給Thread中的TreadLocalMap變量。接着是判斷返回對象map是否爲null對象,如果不是,就初始化Tread中的TreadLocalMap對象,如果是,就用自身作爲key以及value值來創建Entry,存入相應的Thread中,具體存入過程如下

//ThreadLocalMap
private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

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

            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);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

首先根據所在線程取出當前的map,然後查找map中存入的數據並返回,由於之前存的時候存入了TreadLocal對象的值,在取的時候就可直接把TreadLocal對象作爲key進行查找。getEntry的代碼如下

private Entry getEntry(ThreadLocal<?> key) {
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            if (e != null && e.get() == key)
                return e;
            else
                return getEntryAfterMiss(key, i, e);
        }

整體是很簡單的,通過key值在Thread中的TreadLocalMap對象中查找數據。

最後總結一下過程,ThreadLocal通過當前的線程來獲取相應線程中存儲數據的TreadLocalMap,TreadLocalMap就是真正的存儲數據的對象,通過對他進行修改,獲取,就實現了TreadLocal在不同線程中擁有不同的數據的功能。

MessageQueue

MessageQueue用於以隊列的形式存儲消息,即先進先出,但實質上它是以鏈表的形式實現的。其中比較重要的方法有enqueueMessage、next,分別用於消息的添加和取出。
首先我們來看一下enqueueMessage方法:

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

總體邏輯就是根據所給時間when將消息添加到鏈表的適當位置,添加鏈表的邏輯相信大多數人都是會的,就不多說了,重點是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;
                }
				......     

    }

這裏省略了一些不太重要的代碼,可以看出當MessageQueue中沒有消息即代碼中的msg爲null時並且mQuitting爲false時,這個方法將無限循環下去,不斷的讀取是否有消息的加入,阻塞線程。當消息隊列中有消息時,就會讀取消息返回,並且刪除該消息。

Looper

Looper在流程中類似於一箇中間商,不斷的從message中獲取消息,然後傳遞給handler進行處理。每一個線程只會有一個Looper,我們很容易想到它是通過TreadLocal實現的
在它的內部存在着ThreadLocal的靜態對象

	//looper
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

通過ThreadLocal我們就可以使的每一個線程中的Looper的值獨立,不會相互干擾。我們在子線程中使用Looper時,必須先調用prepare方法創建當前線程的Looper

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

前面講了ThreadLocal的實現原理,這裏就不難理解了。簡單的存儲對象罷了。同時我們能看到每一個線程中只能創建一個Looper,否則會報錯。在MainThread中即我們更新UI的線程中,在創建線程時系統便會自動調用prepareMainLooper()爲主線程創建Looper

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

在Looper創建的同時, 會創建MessageQueue

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

也就是說一個Looper對應一個MessageQueue。創建完looper後Looper還並不能開始從消息隊列讀取消息。只有調用了Loop函數才行:

//looper
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;

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

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;// This must be in a local variable, in case a UI event sets the logger
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }
            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            ...     
        }
    }

同樣這裏我們只列出了比較關鍵的代碼。在Loop中,會調用MessageQueue的next方法來獲取消息,同時調用handler的dispatchMessage方法處理消息,只有當msg==null時纔會結束循環,否則如果消息隊列中沒有信息時,next()方法會堵塞,無法返回值,這就使得Loop也被堵塞在那裏。如果需要結束Looper可以調用Looper中的quit和quitSafety方法,
這兩個方法的區別是,quit將直接結束讀取消息,而quitSafety會先將消息隊列中的消息處理完畢,在結束讀取消息。這兩個方法都會調用MessageQueue的quit方法:

//MessageQueue
void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

這裏會改變mQuitting的值爲true。這個值我們在MessageQueue的next就見過:

//MessageQueue中的next()
// Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

返回null之後就能使Looper結束循環,使得方法執行完畢。

Handler

Handler用於發送消息並且處理消息。發送消息可以通過post和send的一系列方法實現,比如:

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

很容易看出發送信息的過程,實質上就是設置消息的target, 再把消息加入到消息隊列中。此後Looper就會通過MessageQueue的next()讀取消息,並且讀取 成功後調用handler的dispatchMessage方法

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

這裏面msg.callback是一個Runnable對象,可以在生成信息時設置。mCallback則是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);
    }

緊接着handleeMessage是Handler中的一個空方法。通過源碼我們很容易知道,我們設置handler如何處理消息時有三種方法:

  • 在消息中設置callback參數
  • 在Handler的構造函數中傳入Callback的實現
  • 重寫Handler中的handleMessage方法

以上三種方式的優先級依次減弱。

碼字不易,謝謝拜讀。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章