【EventBus】EventBus 源码解析 ( 事件发送 | 线程池中执行订阅方法 )
生活随笔
收集整理的這篇文章主要介紹了
【EventBus】EventBus 源码解析 ( 事件发送 | 线程池中执行订阅方法 )
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、EventBus 中主線程支持類
- 二、EventBus 中 AsyncPoster 分析
- 三、AsyncPoster 線程池 Runnable 任務類
一、EventBus 中主線程支持類
從 Subscription subscription 參數中 , 獲取訂閱方法的線程模式 , 根據 【EventBus】Subscribe 注解分析 ( Subscribe 注解屬性 | threadMode 線程模型 | POSTING | MAIN | MAIN_ORDERED | ASYNC) 博客的運行規則 , 執行線程 ;
如果訂閱方法的線程模式被設置為 ASYNC , 則不管在哪個線程中發布消息 , 都會將事件放入隊列 , 通過線程池執行該事件 ;
public class EventBus {private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {// 獲取該 訂閱方法 的線程模式 switch (subscription.subscriberMethod.threadMode) {case ASYNC:asyncPoster.enqueue(subscription, event);break;default:throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);}} }二、EventBus 中 AsyncPoster 分析
AsyncPoster 分析 : 在 EventBus 中 , 定義了 AsyncPoster asyncPoster 成員變量 , 在構造函數中進行了初始化操作 ;
public class EventBus {private final AsyncPoster asyncPoster;EventBus(EventBusBuilder builder) {asyncPoster = new AsyncPoster(this);} }三、AsyncPoster 線程池 Runnable 任務類
AsyncPoster 實現了 Runnable 接口 , 在 run 方法中 , 調用 eventBus.invokeSubscriber(pendingPost) 執行訂閱方法 ;
將該 Runnable 實現類 , 直接傳遞給線程池 , 即可執行 ;
/*** Posts events in background.* * @author Markus*/ class AsyncPoster implements Runnable, Poster {private final PendingPostQueue queue;private final EventBus eventBus;AsyncPoster(EventBus eventBus) {this.eventBus = eventBus;queue = new PendingPostQueue();}public void enqueue(Subscription subscription, Object event) {// 獲取 PendingPost 鏈表PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);// 將 訂閱者 和 事件 加入到 PendingPost 鏈表中 queue.enqueue(pendingPost);// 啟動線程池執行 AsyncPoster 任務eventBus.getExecutorService().execute(this);}@Overridepublic void run() {// 從鏈表中取出 訂閱者PendingPost pendingPost = queue.poll();if(pendingPost == null) {throw new IllegalStateException("No pending post available");}// 執行訂閱方法eventBus.invokeSubscriber(pendingPost);}} 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的【EventBus】EventBus 源码解析 ( 事件发送 | 线程池中执行订阅方法 )的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【EventBus】EventBus 源
- 下一篇: 【EventBus】EventBus 源