天天看點

Handler(上)那些事兒Handler概述ThreadLocalMessageQueueLooper的工作原理局部總結

目錄

  • Handler概述
  • ThreadLocal
    • set
    • get
  • MessageQueue
    • enqueueMessage
    • next
  • Looper的工作原理
    • 構造方法
    • prepare
    • myLooper
    • loop
  • 局部總結

Handler概述

Activity是不能進行耗時操作的,否則會出現ANR無響應,是以如果要進行耗時操作,必須開啟子線程去執行耗時操作.那麼問題來了,UI資料的變化必須在主線程裡實作,子線程是不允許進行UI操作的,這個時候就需要Handler去實作子線程和主線程的通信,是以Handler機制是Android中非常重要的消息通訊機制.是以了解了解學習Handler是非常必要的.

ThreadLocal

這裡Handler的基本使用就不再做過多的講解.為了更好的了解Handler,ThreadLocal作為知識儲備是很有必要學習的,因為在後面的分析中需要和他見面.

ThreadLocal是用來線程間資料的存儲的.怎麼了解?我們來看看下面一段代碼

ThreadLocal<String> threadLocal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        threadLocal = new ThreadLocal<>();
        threadLocal.set("Main");

        new Thread(){
            @Override
            public void run() {
                super.run();
                System.out.println("thread "+threadLocal.get());// thread null
            }
        }.start();

           

我們定義了一個存儲String的ThreadLocal,在主線程去添加一個Main字元串,接着開啟一個子線程去擷取,最終輸出是 thread null,并沒有我們所想的 thread Main.這就展現了線程進的資料存儲,具體咱們實作的咱們來看看關鍵的get 和 set方法.

set

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

我們可以看到我們主要是将資料存儲到ThreadLocalMap中,以目前線程為key,将value存儲起來,這也就為什麼主線程裡set的資料,子線程get不到.因為一個是以主線程為key去擷取資料,一個是以子線程為key去擷取資料,當然擷取不到資料.

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

get方法也一樣,通過目前線程為key.擁有的知識儲備接下來,我們來看看消息隊列的原理.

MessageQueue

我們在使用Handler的時候,傳遞的消息就是Message,那麼這些Message就是添加到MessageQueue隊列中,依次去發送資料的.是以MessageQueue的主要作用就是接管理Message的隊列,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;
    }
           

上訴代碼,我們需要知道四點

  • msg.target就是handler,就是去處理發來message的handler(可以看Message的源碼裡的target)
  • enqueueMessage第二個參數表示執行的時間,是毫秒為機關
  • Message是以單連結清單的形式進行,通過執行的時間去排列插入.
  • Message.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;
        (1) 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) {
        (2) 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;
        }
    }

           

重點來看看(1) (2)處的代碼

  1. 從該處代碼可以看出,消息的讀取其實是死循環一直讀取的.那麼就抛出一個問題,為什麼這樣一直的死循環,app不會卡死?這麼消耗資源為什麼app還是很流程? 該問題留到後面 哈哈
  2. 還記得enqueueMessage方法分析的第四點,message.when表示的是Message索要執行的時間,是以該出代碼就是通過when來判斷是否執行該message,沒有着記錄下還需要等待的時間,可以執行則傳回該message.

next方法主要是一個無線循環的方法,循環的從獨處連結清單中的Message,并且傳回.

Looper的工作原理

Looper的主要作用就是負責綁定目前線程,使消息循環起來.

我們知道,Handler的工作需要Looper,沒有Looper的線程會報錯,那麼如何為一個線程建立Looper呢?其實很簡單,通過Looper#prepare方法,為目前線程建立一個Looper,在通過Looper#loop方法去開啟消息循環.那麼我們來看看方法的源碼.

構造方法

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

           

我們看到,在構造方法中,Looper回去初始化MessageQueue,并且擷取目前線程的線程.

prepare

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

我們可以看到,prepare方法通過ThreadLocal,将目前線程和Looper相綁定.

myLooper

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
           

擷取目前線程所綁定的Looper對象.

loop

public static void loop() {
      (1)  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;

     (2)for (;;) {
          (3)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 {
           (4)   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();
        }
    }

           

上訴代碼主要看這四個關鍵點

  1. loop方法,主要操作邏輯的對象是與目前線程想綁定的Looper對象.
  2. loop方法裡有一個死循環,大部分的業務邏輯都在這個死循環裡
  3. 這個循環裡,不斷循環的調用MessageQueue#next方法,去拿到将要去分發的message事件.
  4. 通過message.target也就是handler,的dispatchMessage方法去回調對應的message方法,進而可以去處理該message.

局部總結

現在我們可以大緻的總結一下,Message MessageQueue Looper ThreadLocal 四者的關系.

  • Message是消息的載體,表示将要分發的消息的内容;
  • MessageQueue則是用于管理消息的載體message,通過enqueueMessage方法将新Message添加到隊列中,next用于從隊列中取出将要執行的Message;
  • Looper則消息隊列的驅使着,通過ThreadLocal将線程和Looper綁定,通過loop方法不斷的調用messageQueue#next方法去擷取将要執行的Message,通過Handler#dispatchMessage回調去操作.

那麼部分人在平時的使用中可能連Looper都沒有用到,單純一個Handler就夠,那麼我們還需要來看看Handler的源碼來一探究竟.

來看看下一遍Handler(下)那些事兒

繼續閱讀