android非同步訊息處理機制
android非同步訊息處理主要由四部分組成:Handler,Looper,Message,MessageQueue
Message:執行緒之間傳遞的訊息,可以在內部攜帶少量訊息
MessageQueue:
Looper:每個執行緒有且最多隻能有一個Looper物件,它是一個ThreadLocal(執行緒本地儲存物件);
(ThreadLocal:實現一個執行緒本地儲存物件,對於一個變數,每個執行緒都要各自的值,所有執行緒共享相同的物件,但是其中一個執行緒中的變數改變不會影響其他執行緒中該變數的值)
/** * Impleandroid非同步訊息處理主要由四部分組成:Handler,Looper,Message,MessageQueue Message:執行緒之間傳遞的訊息,可以在內部攜帶少量訊息 MessageQueue: Looper:每個執行緒有且最多隻能有一個Looper物件,它是一個ThreadLocal(執行緒本地儲存物件); (ThreadLocal:實現一個執行緒本地儲存物件,對於一個變數,每個執行緒都要各自的值,所有執行緒共享相同的物件,但是其中一個執行緒中的變數改變不會影響其他執行緒中該變數的值) /** * Implements a thread-local storage, that is, a variable for which each thread * has its own value. All threads share the same {@code ThreadLocal} object, * but each sees a different value when accessing it, and changes made by one * thread do not affect the other threads. The implementation supports * {@code null} values. * * @see java.lang.Thread * @author Bob Lee */ Looper內部維護了一個MQ,loop()方法呼叫後執行緒開始不斷從佇列中取出訊息執行 Handler:1.用於處理和傳送訊息; 2.建立時關聯一個Looper和Looper中的MQ; 3.一個執行緒可以有多個Handler; 4.Handler可在任意執行緒傳送訊息,訊息會被新增到關聯的MQ中; 5.Handler是在它關聯的Looper執行緒中處理訊息的。 ments a thread-local storage, that is, a variable for which each thread * has its own value. All threads share the same {@code ThreadLocal} object, * but each sees a different value when accessing it, and changes made by one * thread do not affect the other threads. The implementation supports * {@code null} values. * * @see java.lang.Thread * @author Bob Lee */
Looper內部維護了一個MQ,loop()方法呼叫後執行緒開始不斷從佇列中取出訊息執行
Handler:1.用於處理和傳送訊息;
2.建立時關聯一個Looper和Looper中的MQ;
3.一個執行緒可以有多個Handler;
4.Handler可在任意執行緒傳送訊息,訊息會被新增到關聯的MQ中;
5.Handler是在它關聯的Looper執行緒中處理訊息的。