2017-04-23 55 views
0

等待future.isDone()== true返回調用線程(main)的標準方法是什麼?返回可調用結果的非阻塞方法

我試着通過一個asyncMethod()在調用線程(主線程)上返回一個結果。 asyncMethod()立即返回,但在返回之前,首先觸發一個導致廣播意圖回到主線程的進程。在主線程中,我檢查future.isDone(),但不幸的是,future.isDone()僅在一半時間返回true。

 ExecutorService pool = Executors.newSingleThreadExecutor(); 
     Callable<Boolean> callable = new Callable<Boolean>(){ 
      public Boolean call() { 
       Boolean result = doSomething(); 
       callbackAsync(); //calls an async method that returns immediately, but will trigger a broadcast intent back to main thread 
       return result; 
      } 
     }; 

     new broadCastReceiver() { ///back on main thread 
     ... 
      case ACTION_CALLABLE_COMPLETE: 
       if (future.isDone()) // not always true... 
         future.get(); 

} 

回答

0

您可以使用CompletionService一旦準備就緒即可接收期貨。以下是您的代碼示例

ExecutorService pool = Executors.newSingleThreadExecutor(); 
CompletionService<Boolean> completionService = new ExecutorCompletionService<>(pool); 

Callable<Boolean> callable = new Callable<Boolean>(){ 
    public Boolean call() { 
     Boolean result = true; 
     //callbackAsync(); //calls an async method that returns immediately, but will trigger a broadcast intent back to main thread 
     return result; 
    } 
}; 

completionService.submit(callable); 

new broadCastReceiver() { ///back on main thread 
    ..... 
    Future<Boolean> future = completionService.take(); //Will wait for future to complete and return the first completed future 
    case ACTION_CALLABLE_COMPLETE: future.get();