CompletableFuture,在"join"后运行异步代码



几个月后,我在Javascript/Typescript上遇到了一些麻烦。

例如,让我们看看这个片段:
@Test
public void testAsync(){
CompletableFuture.supplyAsync(()->{
try{
Thread.sleep(10000);
System.out.println("After some seconds");
}catch(InterruptedException exc){
return "Fail";
}
return "Done";
}).thenAccept(s->System.out.println(s)).join();
System.out.println("should write before After some seconds statement");
}

我期望最后一个system.out.println在CompletableFuture之前运行,但它等待Future的完成。

所以我得到的是:几秒钟后"Done"After some seconds语句">

我想要的:应该在After some seconds语句前写&;几秒钟后"Done">

我怎么才能做到呢?

将未来存储在变量中,打印语句,然后join()等待结果:

CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(10000);
System.out.println("After some seconds");
} catch (InterruptedException exc) {
return "Fail";
}
return "Done";
}).thenAccept(s -> System.out.println(s));
System.out.println("should write before After some seconds statement");
future.join();

对于解释,.join()方法的javadoc说:

在完成时返回结果值,或者在完成异常时抛出(未检查的)异常

这意味着,如果你调用.join()链接到thenAccept(),这意味着你将首先等待supplyAsync()结束,然后是thenAccept(),并将通过join()等待这样的结果。

因此,您将在所有操作完成后到达System.out.println("should write before After some seconds statement");

如果您的目标是在完成测试之前等待未来,那么您应该在主线程打印之后而不是之前调用join()

最新更新