Handler Looper 源碼分析

1.Hander sendMessage 分析(MessageQueue 消息隊列)

Handler sendMessage以後的流程
Hander.sendMessage(msg) --->Hander.sendMessageDelayed--->Hander.sendMessageAtTime ---> Hander.enqueueMessage ---> MessageQueue.enqueueMessagejava

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) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                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;
            }

            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

複製代碼

目前爲止咱們沒有看到 handler 去調用 handleMessage() 方法 ,目前也只是看到了 MessageQueue , 把消息給了 mMessage
總結:handler.sendMessage其實只是把咱們的Message加入了消息隊列,隊列採用的是鏈表的方式,按照時間排序,而後再也沒幹其餘。bash

2.Loop 消息循環

子線程中使用 Handler 必須先調用 Looper.prepare(); 否則會報錯,咱們在主線程中並無調用過 Looper.prepare(),爲何就不報錯?
由於在咱們應用啓動的時候,ActivityThread 的入口函數 main() 方法中已經寫了
函數

public static void main(String[] args) {
        ...
        Looper.prepareMainLooper();
        ...
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
複製代碼

Looper.prepareMainLooper();
進入源碼查看主要調用 sThreadLocal.set(new Looper(quitAllowed));

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));
    }
複製代碼

sThreadLocal.set(new Looper(quitAllowed));oop

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

總結:其實就是建立一個 Looper ,而且保證一個 Thread 線程中,只有一個 Looper 對象
ui

Looper.loop(); 循環執行MessageQueue裏的message

public static void loop() {        
	 // 獲取線程的 Looper 對象        
	 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;        
	 for (;;) {            
		 // 死循環不斷的獲取 消息隊列中的消息            
		 Message msg = queue.next(); // might block            
		 if (msg == null) {                
			 // No message indicates that the message queue is quitting.               
			 return;            
		 }            
		 try {                
			 // 經過 handler 去執行 Message 這個時候就調用了 handleMessage 方法                
			 msg.target.dispatchMessage(msg);            
		 } finally {                
			 if (traceTag != 0) {                    
			 Trace.traceEnd(traceTag);                
		 }            
		}           
		 // 回收消息            
		 msg.recycleUnchecked();        
	}    
 }
複製代碼

額外知識

msg.recycleUnchecked(); 回收信息
Message 用到 Message 消息池,最大50個,回收消息以後,消息池空閒Message +1this

private static Message sPool;
private static int sPoolSize = 0;
private static final int MAX_POOL_SIZE = 50;
void recycleUnchecked() {
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

複製代碼

Message msg = Message.obtin()Message msg1 = new Message() 區別
Message.obtin() 源碼,先去消息池獲取message(sPool),若是沒有sPool 再從新new Message(); 綜合利用空閒的Message 。spa

public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }
複製代碼
相關文章
相關標籤/搜索