[英]Is it possible to add multiple actions to a CompletableFuture with whenComplete(…)?
The class CompletableFuture
allows to add an action which is called when the future completes after calling complete(...)
. CompletableFuture
类允许添加一个动作,该动作在调用complete(...)
之后将来完成时被调用。
Can I use whenComplete(...)
to add multiple BiConsumer actions for executing when completing the future and are all of them executed when the complete(...)
method is called? 我可以使用
whenComplete(...)
添加多个BiConsumer操作以在将来完成操作时执行这些操作 ,并且在调用complete(...)
方法时是否全部执行了这些操作?
Yes, all BiConsumer actions are added and they are executed in reverse addition order when calling complete(...). 是的,所有BiConsumer操作都已添加,并在调用complete(...)时以相反的添加顺序执行。
An example to demonstrate this might look like this: 演示此示例可能如下所示:
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());
}
}
When running this program, the printed result looks this: 运行该程序时,打印结果如下:
My tests ...
do something else; false
three step(s)
two step(s)
one step(s)
Done true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.