【Android 异步操作】手写 Handler ( 循环者 Looper | Looper 初始化 | Looper 遍历消息队列 MessageQueue )
文章目錄
- 一、Looper 初始化
- 二、Looper 遍歷消息隊列 MessageQueue
- 三、完整 Looper 代碼
一、Looper 初始化
Looper 是 線程本地變量 , 在每個線程中 , 可以通過線程調用 ThreadLocal 變量的 get 方法獲取該線程對應的對象副本 , 調用 ThreadLocal 變量的 set 方法 , 設置該線程對應類型的對象副本 ;
Looper 調用 prepare 方法進行初始化 , 在該方法中處理 線程本地變量的先關初始化與設置 ,
如果之前已經初始化過 , 本次調用 prepare 方法是第二次調用 , 則會 拋出異常 ,
如果之前沒有初始化過 , 那么創建一個 Looper , 然后調用線程本地變量 ThreadLocal 的 set 方法 , 將該 Looper 對象設置成線程本地變量 ;
/*** 一個線程只能有一個 Looper* 使用 ThreadLocal 來保存該 Looper* 是線程內部存儲類 , 只能本線程才可以得到存儲的數據 ;*/static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();/*** 準備 Looper 方法*/public static void prepare(){System.out.println("prepare 創建 Looper ");// 先進行判斷 , 如果當前線程已經有了 Looper , 那就拋出異常if(sThreadLocal.get() != null){throw new RuntimeException("當前線程已存在 Looper");}// 如果不存在 Looper , 就創建一個 LoopersThreadLocal.set(new Looper());}二、Looper 遍歷消息隊列 MessageQueue
在 Looper 線程中 , 最后一句代碼肯定是 Looper.loop() , 執行該方法后 , 就開啟了一個無限循環 ,
不斷從 消息隊列 MessageQueue 中獲取消息 , 然后發送給該 消息 Message 對應的 Handler ,
哪個 Handler 發送的消息 , 就將消息在送回給哪個 Handler ;
消息同步 : 當 消息隊列 MessageQueue 為空時 , 無法從消息隊列中獲取數據 , 此時線程會 阻塞 , 直到有新的消息到來后 , 解除阻塞 ;
Looper 循環遍歷消息隊列部分代碼 :
/*** 不斷從 消息隊列 MessageQueue 中取出 Message 消息執行*/public static void loop(){System.out.println("開始無限循環獲取 Message");// 獲取當前線程的 LooperLooper looper = Looper.looper();// 從當前線程的 Looper 獲取 消息隊列 MessageQueueMessageQueue messageQueue = looper.mQueue;// 不斷從 消息隊列中獲取 消息 , 分發到發送消息的 Handler 中執行for(;;){// 獲取消息隊列中的第一個消息Message next = messageQueue.next();// 分發到發送該消息的 Handler 中執行next.target.handleMessage(next);}}三、完整 Looper 代碼
package kim.hsl.handler;public class Looper {/*** 一個線程只能有一個 Looper* 使用 ThreadLocal 來保存該 Looper* 是線程內部存儲類 , 只能本線程才可以得到存儲的數據 ;*/static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<>();/*** 消息隊列*/public MessageQueue mQueue;/*** Looper 構造函數*/private Looper(){mQueue = new MessageQueue();}/*** 獲取當前線程對應的 Looper* @return*/public static Looper looper(){return sThreadLocal.get();}/*** 準備 Looper 方法*/public static void prepare(){System.out.println("prepare 創建 Looper ");// 先進行判斷 , 如果當前線程已經有了 Looper , 那就拋出異常if(sThreadLocal.get() != null){throw new RuntimeException("當前線程已存在 Looper");}// 如果不存在 Looper , 就創建一個 LoopersThreadLocal.set(new Looper());}/*** 不斷從 消息隊列 MessageQueue 中取出 Message 消息執行*/public static void loop(){System.out.println("開始無限循環獲取 Message");// 獲取當前線程的 LooperLooper looper = Looper.looper();// 從當前線程的 Looper 獲取 消息隊列 MessageQueueMessageQueue messageQueue = looper.mQueue;// 不斷從 消息隊列中獲取 消息 , 分發到發送消息的 Handler 中執行for(;;){// 獲取消息隊列中的第一個消息Message next = messageQueue.next();// 分發到發送該消息的 Handler 中執行next.target.handleMessage(next);}}}
總結
以上是生活随笔為你收集整理的【Android 异步操作】手写 Handler ( 循环者 Looper | Looper 初始化 | Looper 遍历消息队列 MessageQueue )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Android 异步操作】手写 Han
- 下一篇: 【Android 异步操作】手写 Han