日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【EventBus】EventBus 源码解析 ( 事件发送 | 线程池中执行订阅方法 )

發布時間:2025/6/17 编程问答 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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 源码解析 ( 事件发送 | 线程池中执行订阅方法 )的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。