流式调用

CompletionStage有约40个方法是为函数式编程做准备的,通过CompletionStage提供的接口,可以在一个执行结果上进行多次流式调用,以此得到最终结果。

例子,异步计算100的2次方,然后转换成字符串+str,最后输出。

supplyAsync()方法执行一个异步任务,接着连续使用流式调用对任务的处理结果进行再加工,直到最后输出结果。

private void test() {
final int num = 100;
final CompletableFuture future =
CompletableFuture.supplyAsync(()->calculate(num))
.thenApply(x -> Integer.toString(x))
.thenApply((str) -> num + "的平方: " + str)
.thenAccept(System.out::println);
try {
future.get();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("exit");
}
private int calculate(int x) {
int res = 0;
try {
Thread.sleep(1000);
res = x * x;
}catch (InterruptedException ie) {
ie.printStackTrace();
}
return res;
}

输出结果:

Java平方怎么打 java平方函数_随机数

用CompletableFuture异步流式调用,计算随机生成10个1~100的随机数并求和,然后对求得的和计算其平方的值,最后打印。