Android線程之消息機制(Handler、MessageQueue、Looper、Thread)

注意:本篇文章是本人閱讀相關文章所寫下的總結,方便以后查閱,所有內容非原創,侵權刪。

本篇文章內容來自于:

  1. Android開發藝術探索 任玉剛
  2. 深入源碼解析Android中的Handler,Message,MessageQueue,Looper

目錄

  1. 什么是Android消息機制
  2. Android消息機制概述
  3. Android消息機制分析
    --3.1 ThreadLocal的工作原理
    --3.2 MessageQueue的工作原理
    --3.3 Looper的工作原理
    --3.4 Handler的工作原理

1. Android消息機制成員介紹

Android的消息機制主要是指Handler的運行機制。
Handler的運行需要底層的MessageQueue和Looper的支撐。

(1) Handler
Handler是Android消息機制的上層接口,開發時只需和Handler交互即可。
Handler使用很簡單,可以輕松將一個任務切換到Handler所在的線程中去執行。

為什么Androd要提供這個功能:
因為Android規定必須在主線程中訪問UI,又不建議在主線程中進行耗時操作,否則會導致程序無法響應ANR。如果沒有Handler無法將子線程中訪問UI的工作切換到主線程中去進行。

為什么不允許在子線程中訪問UI?
因為Android的UI并不是線程安全的,如果在多線程并發訪問可能會導致UI控件處于不可預期的狀態。如果加上鎖機制會讓UI訪問的邏輯變復雜影響效率。最簡單高效的方法是采用單線程模型來處理UI操作,開發者只需要通過Handler切換線程。

(2) MessageQueue消息隊列:
MessageQueue內部存儲了一組消息,以隊列的形式對外提供給插入和刪除的工作。內部存儲結構并不是真正的隊列,而是采用單鏈表的數據結構來存儲消息列表。

(3) Looper消息循環:
它的出現是因為MessageQueue只是一個消息的存儲單元,不能處理消息。Looper填補了這個功能。
Looper會以無限循環的形式去查找是否有新消息,如果有的話處理消息,否則就一直等待。
線程是默認沒有Looper的,如果需要使用Handler則必須為線程創建Looper。(主線程ActivityThread創建時會初始化Looper,所以在主線程中默認可以使用Handler)

ThreadLocal
Looper中還有一個ThreadLocal。ThreadLocal不是線程,它的作用是可以在每個線程中存儲數據。
Handler創建的時候會采用當前線程的Looper來構造消息循環系統。

那么Handler內部如何獲取當前線程的Looper呢?
這就要使用ThreadLocal。Looper類中使用ThreadLocal來存儲Looper對象。

那么為什么需要ThreadLocal來存儲Looper呢?
因為Looper的構造函數是私有的,無法創建Looper進行賦值。只能將Looper的引用存在變量中,而且每個線程都有自己對應的Looper,則需要用到ThreadLocal來存儲。因為ThreadLocal可以在不同的線程中互不干擾的存儲并提供數據,通過ThreadLocal可以輕松獲取每個線程的Looper。

2. Android消息機制概述

Android的消息機制主要是指Handler的運行機制以及Handler所附帶的MessageQueue和Looper的工作過程。

Handler創建時會采用當前線程的Looper來構建內部的消息循環系統。
如果當前線程沒有Looper,則會報錯。因為線程是默認沒有Looper的,而主線程ActivityThread創建時會初始化Looper,所以在主線程中默認可以使用Handler。
那么如何解決?只需要為當前線程創建Looper即可,或者在一個有Looper的線程中。
Handler創建完畢后,這個時候其內部的Looper以及MessageQueue就可以和Handler一起切同工作了。
發送消息時,可通過Handler的post方法發送一個Runnable,或者通過Handler的send方法發送一個Message。兩個方法都是通過send方法來完成。
當Handler的send方法被調用時,它會調用MessagQueue的enqueueMessage方法將這個消息放入消息隊列,然后Looper發現有新消息到來時,就會處理這個消息。
最終消息中的Runnable或者Handler的HandlerMessage方法會被調用

當使用Handler來post/send消息時,僅僅是向消息隊列中插入了一條消息,MessageQueue的next方法就會返回這條消息給Looper,Looper接受到消息后就開始處理,最終消息由Looper交由給Handler處理,即Handler的dispatchMessage方法會被調用,而Handler的dispatchMessage方法會進行判斷,如果發送過來的是一個runnbale,則運行這個runnable任務;如果mCallback不為null,則運行mCallback的handlerMessage方法;最后運行自身的handleMessage方法

3. Android消息機制分析

3.1 ThreadLocal的工作原理

ThreadLocal是一個線程內部的數據存儲類,通過它可以在指定的線程中存儲數據,數據存儲后,只能在指定線程中可以獲取到存儲的數據,對于其他線程來說則無法獲取到數據。

應用的場景:當某些數據是以線程為作用域并且不同線程具有不通過的數據副本的時候,就可以采用ThreadLocal。
應用:AcivityThread、Looper、AMS
由于不同的線程擁有不同的Looper,則可以通過ThreadLocal來輕松實現Looper在線程中的讀取。

ThreadLocal的使用

public class MainActivity extends BaseActivity {
    private ThreadLocal<Boolean> threadLocal = new ThreadLocal<Boolean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        threadLocal.set(true);
        Log.d("xl", "mainthread=" + threadLocal.get());

        new Thread("thread1") {
            @Override
            public void run() {
                threadLocal.set(false);
                Log.d("xl", "thread1=" + threadLocal.get());
            }
        }.start();

        new Thread("thread2") {
            @Override
            public void run() {
                Log.d("xl", "thread2=" + threadLocal.get());
            }
        }.start();
    }

}
D/xl: mainthread=true
D/xl: thread1=false
D/xl: thread2=null

為什么ThreadLocal可以在不同的線程中維護一套數據的副本并且彼此不干擾?
因為不同線程訪問同一個ThreadLocal的get方法,ThreadLocal內部會從各自的線程中取出一個數組,然后再從數組中根據當前ThreadLocal的索引去查找出對應的value值。很顯然,不同線程中的數組是不同的。

ThreadLocal的內部實現
ThreadLocal是一個泛型類,定義為public class ThreadLocal<T>,只要弄清楚ThreadLocal的get和set方法就可以明白他的工作原理。
(1)ThreadLocal的set方法

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t); //首先獲得當前線程的ThreadLocalMap數據。
        //Thread中有ThreadLocal.ThreadLocalMap threadLocals = null;用于存儲ThreadLocal對象,以Entry的形式
        if (map != null)
            map.set(this, value); //有的話設置
        else
            createMap(t, value); //沒有的話創建
    }

(2)ThreadLocal的get方法

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);//首先獲得當前線程的ThreadLocalMap數據。
        if (map != null) { //有的話則取
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue(); //沒有的話創建
    }

3.2 MessageQueue的工作原理

MessageQueue主要包含兩個操作:插入和讀取。讀取操作本身會伴隨著刪除操作。
插入的操作對應enqueueMessage方法,往消息隊列中插入一條消息。
讀取的操作對應next方法,從消息隊列中取出一條消息并將其從消息隊列中移除。

雖然MessageQueue叫消息隊列,但是內部實現是用了一個單鏈表的數據結構來維護消息列表,因為單鏈表在插入和刪除上比較有優勢。

MessageQueue的內部實現
(1)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;
    }

(2)next
next方法是一個無限循環的方法,如果消息隊列中沒有消息,那么next方法就會阻塞,當有消息到來的時候,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;
        }
    }

3.3 Looper的工作原理

Looper在消息機制中扮演消息循環的角色。它會不停從MessageQueue中查看是否有新消息,如果有新消息就會立刻處理,否則就一直阻塞在那里。

Looper的構造方法(private)
構造方法中會創建一個MessageQueue消息隊列,然后將當前線程的對象保存起來。

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

Handler的工作需要Looper,沒有Looper的線程就會報錯。
那么如何為一個線程創建Looper?
通過Looper.prepare()可為當前線程創建一個Looper,接著通過Looper.loop()來開啟消息循環。

        new Thread("thread1") {
            @Override
            public void run() {
                Looper.prepare();  
                //Looper. prepareMainLooper()這個方法是給主線程創建Looper使用的。
                Handler handler = new Handler();
                Looper.loop();
            }
        }.start();

如何得到當前線程的Looper對象?
getMainLooper()方法,可以在任何地方獲取到主線程的Looper。
Looper.myLooper()拿到當前線程的Looper的引用
如何退出Looper
Looper提供了quit和quitSafely來退出一個Looper。
quit會直接退出Looper。
quitSafely只是設定一個退出標記,會把消息隊列中的已有消息處理完畢后才安全的退出。
Looper退出后,通過Handler發送的消息會失效,此時Handler的send方法會返回false。
在子線程中,如果手動創建了Looper,那么在所有的事情完成后應該調用quit方法來終止消息循環,否則這個子線程會一直處于等待的狀態。

Looper的內部實現
(1)Looper.prepare()方法
會創建一個Looper對象,且用ThreadLocal保存這個對象,ThreadLocal內部是使用當前線程中的一個數組來保存這個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));
    }

(2)Looper.loop()方法
loop方法是一個死循環,
唯一跳出循環的方式是MessageQueue的next方法返回了null。
當Looper的quit方法被調用時,Looper就會調用MessageQueue的quit或者quitSafely方法來通知消息隊列退出,此時next方法會返回null。
所以,除非Looper退出,否則loop方法會無限循環下去。

loop方法會調用MessageQueue的next方法獲取新消息,而next是一個阻塞操作,當沒有消息時,next方法會一直阻塞在那里,這也導致loop方法一直阻塞在那里。
當MessageQueue的next方法返回了新消息后,Looper就會處理這條消息:msg.target.dispatchMessage(msg);
msg.target是發送這條消息的Handler對象,這樣Handler發送的消息最終又交給該Handler的dispatchMessage方法來處理了。
而Handler的dispatchMessage方法是在創建Handler時所使用的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();

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

3.4 Handler的工作原理

Handler的工作主要包括消息的發送和接受過程。
消息的發送可以通過post的一系列方法以及send的一系列方法來實現,其實post也就是用了send方法

    public final boolean dsendMessage(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);
    }

Handler發送消息僅僅是向消息隊列中插入了一條消息,MessageQueue的next方法就會返回這條消息給Looper,Looper接受到消息后就開始處理,最終消息由Looper交由給Handler處理,即Handler的dispatchMessage方法會被調用,這是Handler進入處理消息的階段。

    public void dispatchMessage(Message msg) {
       //1. 首先檢查Message的callback是否為null,不為null則調用handleCallback
      //Message的callback是一個runnable對象,實際上就是Handler的post方法所傳遞的runnable對象,handleCallback就是message.callback.run(),運行runnable。
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                //2.檢查mCallback是否為null,不為null則調用mCallback的handleMessage方法。即new Handler(callback)
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //3.最后調用Handler的handleMessage方法來處理消息
            handleMessage(msg);
        }
    }

為什么在沒有Looper的子線程創建Handler會拋異常
因為public Handler()實際就是調用了Handler(Looper looper)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。