[英]Executing a method in Java after either prior asynchronous methods are done?
I'm trying to use Completetable future to run two task in async. 我正在尝试使用Completetable将来异步运行两个任务。 The program runs asynchronously, such that a() and b() run first, in any order, concurrently.
该程序异步运行,因此a()和b()首先以任意顺序并行运行。 But c() can only run after either one of a() or b() completes
但是c()仅在a()或b()之一完成后才能运行
class Pair{
public void pair2() throws InterruptedException, ExecutionException {
CompletableFuture<Void> fa = CompletableFuture.runAsync(() -> a());
CompletableFuture<Void> fb = CompletableFuture.runAsync(() -> b());
if(fa.isDone || fb.isDone){ //should not be if loop.
c();
}
return;
}
public void a(){
System.out.println("I'm a.");
return;
}
public void b(){
System.out.println("I'm b.");
return;
}
public void c(){
System.out.println("I'm c, I cannot be the first!");
return;
}
}
I'm not familiar with the CompletableFuture API, is there a way to check if either of the task is done and call upon the next method C? 我对CompletableFuture API并不熟悉,有没有一种方法可以检查任务是否已完成并调用下一个方法C?
You could use one of the xxxEither
methods. 您可以使用
xxxEither
方法之一。 For example: 例如:
CompletableFuture<Void> fc = fa.acceptEither(fb, v -> c());
Or you could use the anyOf
method: 或者,您可以使用
anyOf
方法:
CompletableFuture.anyOf(fa, fb).thenRun(this::c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.