2017-04-23 14 views
0

future.isDone()== trueの呼び出し元スレッド(main)を待つ標準的な方法は何ですか?呼び出し可能な結果を​​返すノンブロッキングメソッド

私はasyncMethod()を使って呼び出し側のスレッド(メインスレッド)で結果を返そうとしました。 asyncMethod()は直ちに戻りますが、返す前に、最初にメインスレッドにブロードキャストインテントを返すプロセスをトリガします。メインスレッドでは、future.isDone()がチェックされていますが、残念ながらfuture.isDone()は時間の半分を返します。

答えて

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(); 
関連する問題