return 可调用结果的非阻塞方法

non-blocking method to return callable result

在可调用对象的调用线程(主)上等待 future.isDone()==true 的标准方法是什么?

我尝试通过 asyncMethod() 在调用线程(主线程)上返回结果。 asyncMethod() returns 立即,但在返回之前,首先触发一个进程,该进程导致将广播意图返回到主线程。在主线程中,我检查 future.isDone(),但不幸的是 future.isDone() 只有一半时间 returns 正确。

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

}

您可以使用 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();