CompletableFuture允许添加一个动作,该动作在调用complete(...)之后的将来完成时被调用。

我可以使用whenComplete(...)添加多个BiConsumer操作以在将来完成操作时执行这些操作,并且在调用complete(...)方法时是否全部执行了这些操作?

最佳答案

是的,所有BiConsumer动作均已添加,并在调用complete(...)时以相反的添加顺序执行。

演示此示例可能如下所示:

public class Application {
    public static void main(String[] args) {
        System.out.println("My tests ...");
        CompletableFuture<String> futureString = new CompletableFuture<String>();
        futureString.whenComplete((s,e)->System.out.println("one " + s));
        futureString.whenComplete((s,e)->System.out.println("two " + s));
        futureString.whenComplete((s,e)->System.out.println("three " + s));
        System.out.println("do something else; "+ futureString.isDone());
        futureString.complete("step(s)");
        System.out.println("Done " + futureString.isDone());
    }
}


运行该程序时,打印结果如下:

My tests ...
do something else; false
three step(s)
two step(s)
one step(s)
Done true

10-02 09:26