我有一个调用其他异步函数的异步函数。在Java中,如何等待异步调用完成(包括其中任何嵌套的异步调用)。
我已经可以 future 调用,但运气不好。
示例代码:
void asyncMehodA(){ }
void asyncMethodB() {
asyncMehodA();
}
我通过以下方式尝试了 Future 可调用:
final Callable<Void> callable1 = new Callable<Void>() {
@Override
public Void call() {
asyncMethodB();
return null;
}
};
final Future<Void> callableFuture = mExecutor.submit(callable1);
try {
callableFuture.get();
} catch (final InterruptedException | ExecutionException e) {}
希望 get 函数会阻止执行,直到异步返回。但似乎 get 函数会触发异步调用并返回 null。不等待 asycn 完成其执行。我在验证中添加了相同的日志语句。如果我的理解有误,请指正。建议任何其他可以帮助我的概念。
最佳答案
这是一个使用 CountDownLatch 的示例.
package chapter13;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class BST {
public static void main(String[] args) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final ExecutorService executorService = Executors.newCachedThreadPool();
Runnable runnableA = () -> {
System.out.println("Runnable A");
latch.countDown();
System.out.println("Runnable A finished");
};
Runnable runnableB = () -> {
System.out.println("Runnable B");
executorService.submit(runnableA);
try {
System.out.println("Runnable B waiting for A to complete");
latch.await();
System.out.println("Runnable B finished");
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
Thread.currentThread().interrupt();
}
};
executorService.submit(runnableB);
Thread.sleep(10);
shutDown(executorService);
}
private static void shutDown(ExecutorService executorService) {
executorService.shutdown();
try {
if (!executorService.awaitTermination(1, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
}
}
我使用 Thread.sleep() 方法来 sleep 主线程,因为在任务 B 提交后立即关闭池,可能会导致池在任务 A 提交之前停止接受新任务通过任务 B。
关于java - 等待java异步调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445286/