2017-04-23 6 views
0

Was ist die Standardmethode, um auf future.isDone() == true zurück auf den aufrufenden Thread (main) der aufrufbaren warten?Nicht blockierende Methode, um aufrufbares Ergebnis zurückzugeben

Ich habe versucht, ein Ergebnis auf den aufrufenden Thread (Haupt-Thread) durch eine asyncMethod() zurückgeben. AsyncMethod() gibt sofort zurück, löst jedoch vor der Rückgabe zuerst einen Prozess aus, der zu einer Broadcast-Absicht zurück zum Hauptthread führt. Im Hauptthread schaue ich nach future.isDone(), aber leider gibt future.isDone() nur die Hälfte der Zeit zurück.

 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(); 

} 

Antwort

0

können Sie ein CompletionService verwenden, um das Futures so schnell zu erhalten, sobald sie bereit sind. Hier ist ein Beispiel mit Ihrem Code

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(); 
Verwandte Themen