2016-11-30 88 views
0

我有三個任務提交給執行程序實例。我需要通知兩個活動,即同步過程結束。所以我有這樣等待將來在處理程序線程中獲得結果

公共類SyncManager {

Handler syncHandler; 

public SyncManager() { 
    initHandler(); 
} 

private void initHandler() { 
    HandlerThread ht = new HandlerThread("syncHandler"); 
    ht.start(); 
    syncHandler = new Handler(ht.getLooper()) { 
     private ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(3); 

     public void handleMessage(Message msg) { 

      Future future1 = executor.submit(new ImageRetrieverTask()); 
      Future future2 = executor.submit(new FileRetrieverTask()); 
      Future future3 = executor.submit(new AudioRetrieverTask()); 


      try { 
       Object result1 = future1.get(); 
       Object result2 = future2.get(); 
       Object result3 = future3.get(); 

     // Here i can use EventBus to notify observers of the completion of the sync 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } catch (ExecutionException e) { 
       e.printStackTrace(); 
      } 
     }; 
    }; 
} 

public void performSync() { 
    syncHandler.sendEmptyMessage(1); 
} } 

當SyncManager類分配,處理程序被初始化實現它。 當調用performSync方法時,它基本上會向處理程序發送一條消息,以將所有同步相關任務添加到執行程序,以便它可以執行它們。處理程序是等待直到期貨結束的後臺循環,以便可以通過EventBus分派通知。處理程序是這樣,我可以在後臺線程中等待。

我覺得這是做這件事的一種詭計。有沒有更好的方法來做到這一點?

任何幫助,非常感謝。 謝謝!

+0

它通常使用Rxjava這類任務的完成不重用ThreadPoolExecutor你可以等待。有關更多詳細信息,請參閱此博客:https://www.captechconsulting.com/blogs/getting-started-with-rxjava-and-android –

回答

0

如果你不使用Future結果,直到所有提交的任務通過調用ExecutorService.awaitTermination(long timeout, TimeUnit unit)