《深入理解Android內核設計思想》學習筆記:第五章 Android進程、線程管理

一、進程和線程

  • 進程:進程(process)是程序的一個運行實例;
  • 線程:線程(Thread)是CPU調度的一個基本單元;
  • Android:
    • 四大組件只是進程中的一些“零件”;
    • 應用程序啓動後,至少創建一個主線程Activity Thread,兩個Binder線程;
    • 同一個包中的組件將運行在相同的進程空間內;
    • 不同的包中組件可以通過一定的方式(IPC)運行在同一個進程空間內;

二、Thread、Looper、Message、Hanlder直接的關係

1、一個線程Thread對應一個Looper

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

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

在一個線程裏邊Looper.prepare(),這個Looper就創建了一個MessageQueue(),同時指定Looper的線程爲當前線程。

2、一個Looper對應一個MessageQueue

上述已足夠說明

3、每個MessageQueue有N個Message

上述已足夠說明

4、每個Messag最多指定一個Hanlder來處理

public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }

    mLooper = Looper.myLooper();//當前線程的mLooper
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;//這個Looper的mQueue
    mCallback = callback;
    mAsynchronous = async;
}

我們可以在一個線程Thread中new一個Hanlder,這個Hanlder會找到當前線程的mLooper,以及這個Looper的mQueue。

 /**
 * Subclasses must implement this to receive messages.
 */
public void handleMessage(Message msg) {
}
  /**
 * Handle system messages here.
 */
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

上述爲默認的分發執行Message的策略,當然也可以複寫自定義。最終執行的就是handleMessage(msg)。

Thread和Hanlder是一對多的關係

上述可知,我們可以在一個Thread裏邊new出多個Hanlder,這個Hanlder會找到當前的Thead公共的唯一的Looper以及這個Looper的唯一的MessageQueue,我們通過Hanlder將一些Message壓入到MessageQueue裏邊。這個Looper會從Queue裏邊一個個取出Message,然後交給Hanlder來處理。

總結

我們可以將一個App看做一個應用程序,啓動程序默認會啓動一個進程,這個進程啓動時就會zygoteInit啓動一個主線程和兩個binder線程以及我們自己new的一些子線程。其中這個主線程就是ActivityThread(Service也是寄存在ActivityThread之中的)。然後通過上述的Handler、Looper、MessageQueue,讓程序活了起來。

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