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

时间:2017-11-24 10:49:13

标签: java completable-future

我尝试使用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?

1 个答案:

答案 0 :(得分:2)

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

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

或者您可以使用anyOf方法:

CompletableFuture.anyOf(fa, fb).thenRun(this::c);
相关问题