天天看點

Android消息機制解析

Android消息機制原了解析

Android消息機制解析

為什麼主線程中可以直接使用Handler?

Handler 的運作需要底層的 MessageQueue 和 Looper 支撐,MessageQueue 是以單連結清單為資料結構的消息清單,Looper 以無限循環的形式去查找 MessageQueue 中是否有新消息需要處理。Looper 中還有一個特殊概念 ThreadLocal,可以在不同的線程中互補幹擾地存儲并提供資料,通過 ThreadLocal 可以輕松擷取每個線程的 Looper。線程預設沒有 Looper,如果需要使用 Handler 就必須為線程建立 Looper。而主線程,也就是 ActivityThread,它在建立時會初始化 Looper,這就是在主線程中預設可以使用 Handler 的原因。

為什麼Android會提供Handler?

Android 規定通路 UI 隻能在主線程中進行,如果子線程中通路 UI,那麼程式就會抛出異常。ViewRootImpl 對 UI 操作做了驗證,該驗證過程是由 checkThread 方法完成的:

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

同時 Android 又建議在主線程中不要進行耗時操作,否則導緻程式無法響應即 ANR。而在系統提供 Handler,正是為了解決子線程中無法通路 UI 的沖突。

為什麼不允許子線程中通路UI呢?

這是因為 Android 的 UI 控件時線程不安全的,如果多線程中并發通路可能導緻 UI 控件處于不可預期的狀态。

為什麼系統不對UI的通路加上鎖機制呢?

首先加上鎖機制會讓 UI 通路邏輯變得負責,其次鎖機制會降低 UI 的通路效率,阻塞某些線程的執行。鑒于以上兩個缺點,最簡單且高效的方法就是采用單線程模型來處理 UI 元件。

Handler的處理過程

Handler 建立完畢後,内部的 Looper 及 MessageQueue 就可以和 Handler 一起協同工作。通過 Handler 的 post 方法将一個 Runnable 投遞到 Handler 内部的 Looper 中去處理,也可以通過 Handler 的 send 方法發送一個消息,該消息同樣會在 Looper 中處理。而 post 方法最終也是通過 send 方法來完成的。

當 Handler 的 send 方法調用時,會調用 MessageQueue 的 enqueueMessage 方法将這個消息放到消息隊列中,然後 Looper 發現有消息來時就會處理這個消息,最終消息中的 Runable 或 Handler 的 HandlerMessage 方法就會被調用。而 Looper 是運作在 Handler 所線上程中,這樣一來 Handler 中的業務就被切換到建立 Handler 所在的線程中去執行了。

Android消息機制解析

ThreadLocal (Java8)

運用場景

  1. 存儲目前線程的資料
  2. 複雜邏輯下的對象傳遞

内部原理

ThreadLocal 是一個泛型類,其定義為 public class ThreadLocal ,是以弄清楚 ThreadLocal 的 get 和 set 方法就可以明白其工作原理。

先看 set 方法:

public void set(T value) {
     //1、擷取目前線程
     Thread t = Thread.currentThread();
     //2、擷取線程中的屬性 threadLocalMap ,如果threadLocalMap 不為空,
     //則直接更新要儲存的變量值,否則建立threadLocalMap,并指派
     ThreadLocalMap map = getMap(t);
     if (map != null)
         map.set(this, value);
     else
         // 初始化thradLocalMap 并指派
         createMap(t, value);
 }
           

ThreadLocalMap 是 ThreadLocal 的内部靜态類,而它的構成主要是用 Entry 來儲存資料 ,而且還是繼承的弱引用。在 Entry 内部使用 ThreadLocal 作為 key,使用我們設定的 value 作為 value。

static class ThreadLocalMap {
 /**
   * The entries in this hash map extend WeakReference, using
   * its main ref field as the key (which is always a
   * ThreadLocal object).  Note that null keys (i.e. entry.get()
   * == null) mean that the key is no longer referenced, so the
   * entry can be expunged from table.  Such entries are referred to
   * as "stale entries" in the code that follows.
   */
    static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
        Object value;
        Entry(ThreadLocal<?> k, Object v) {
            super(k);
            value = v;
        }
    }
}
           
//這個是threadlocal 的内部方法
void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
}
 
//ThreadLocalMap 構造方法
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY];
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}
           

ThreadLocalMap 其實是 Thread 線程的一個屬性值,而 ThreadLocal 是維護 ThreadLocalMap。ThreadLocal 的 get 方法如下:

public T get() {
    //1、擷取目前線程
    Thread t = Thread.currentThread();
    //2、擷取目前線程的ThreadLocalMap
    ThreadLocalMap map = getMap(t);
    //3、如果map資料為空,
    if (map != null) {
        //3.1、擷取threalLocalMap中存儲的值
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    //如果是資料為null,則初始化,初始化的結果,TheralLocalMap中存放key值為threadLocal,值為null
    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;
}
           

參考部落格:史上最全ThreadLocal 詳解(一)

MessageQueue工作原理

MessageQueue 組要包含兩個操作:插入和讀取。讀取操作本身伴随着删除操作,插入和讀取對應的方法分别為 enqueueMessage 和 next。MessageQueue 是通過一個單連結清單的資料結構來維護消息清單,在插入和删除上比較有優勢。

enqueueMessage 源碼如下:

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

next 源碼如下:

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

Looper工作原理

Looper 在 Android 消息機制中扮演着消息循環角色,它會不停從 Message 中檢視是否有新消息進行處理,沒有則一直阻塞。其構造函數如下:

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

Handler 工作需要 Looper,一個線程通過 Looper.prepare() 來建立一個 Looper,接着通過 Looper.loop() 來開啟消息循環。

new Thread("ThreadName"){
    @Override
    public void run(){
        Looper.prepare();
        Handler handler = new Handler();
        Looper.looper();
    }
}.start();
           

Looper 除了 prepare 方法外,還提供了 prepareMainLooper 方法,該方法主要是給 ActivityThread 建立 Looper 使用的,本質也是通過 prepare 來實作的。此外,Looper 還提供了一個 getMainLooper 方法,通過它可以在任何地方擷取到主線程的 Looper。Looper 也是可以退出的,它提供了 quit 和 quitSafely 來退出一個 Looper,兩者差別在于 quit 會直接退出,而 quickSafely 隻是設定一個退出辨別,然後把消息隊列的已有消息處理完畢後才安全退出。

Looper 在調用 loop 方法後,消息循環系統才會真正起作用,其實作如下所示:

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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; 

        // 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 (;;) {
            //queue.next()是一個阻塞方法,沒有消息時一直阻塞
            Message msg = queue.next(); // might block
            if (msg == null) {
                //消息為空時則跳出循環		
                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為發送該消息的Handler對象
                //發送的消息最終通過dispatchMessage()進行處理
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
            }

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

Handler工作原理

Handler 的工作主要包含消息的發送和接收過程,消息的發送通過 post 的一系列方法以及 send 的一系列方法來實作。

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

    
    public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }
           

可以發現,Handler 發送消息的過程僅僅時向消息對列中插入了一條消息,MessageQueue 的 next 方法就會傳回這條消息給 Looper,Looper 接收後開始處理,最終消息由 Looper 交由 Handler 處理,即 Handler 的 dispatchMessage 方法調用。

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

Message 的 callback 是一個 Runnable 對象,實際上就是 Handler 的 post 方法傳遞的 Runnable 參數。handleCallback 的邏輯如下:

private static void handleCallback(Message message) {
     message.callback.run();
 }
           

當 mCallback 不為 null 時就調用 mCallback 的 handleMessage 方法來處理消息,其定義如下:

/**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of 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 還有一個特殊的構造方法,就是通過一個特定的 Looper 來構造 Handler,其實作如下:

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

Handler 的預設構造方法 public Handler() 會調用如下的構造方法,解釋了在沒有 Looper 的子線程中會引發程式異常的原因。

public Handler(Callback callback, boolean async) {
       ...
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }
           

參考書籍:《Android開發藝術探索》/任玉剛 | 電子工業出版社