在任一先前的异步方法完成后执行 Java 中的方法?

Executing a method in Java after either prior asynchronous methods are done?

我正在尝试使用 Completetable future 来 运行 两个异步任务。程序 运行 是异步的,因此 a() 和 b() 运行 首先,以任何顺序同时进行。但是 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;
  }
}

我不熟悉 CompletableFuture API,有没有办法检查是否完成了任一任务并调用下一个方法 C?

您可以使用 xxxEither 方法之一。例如:

CompletableFuture<Void> fc = fa.acceptEither(fb, v -> c());

或者您可以使用 anyOf 方法:

CompletableFuture.anyOf(fa, fb).thenRun(this::c);