Java CompletableFuture
继承了 CompletionStage
和 Future
接口。 CompletableFuture.thenApply
继承自 CompletionStage
。 thenApply
返回一个新的 CompletionStage
,当此阶段正常完成时,将使用此阶段的结果作为所提供函数的参数来执行该 CompletionStage
。
从 Java 文档中找到 thenApply
的方法声明。
<U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn)
类型参数 U 是函数的返回类型。
fn 参数是用于计算返回的 CompletionStage
值的函数。thenApply
方法返回一个 CompletionStage
。
thenApply()
可用于对另一个任务的结果执行一些额外的任务。现在找到例子。
示例 1:我们创建一个 CompletionStage
来执行某些任务,然后在此阶段的结果中,我们应用一个函数来使用 thenApply
执行其他任务。找到例子。
ThenApplyDemo1.java
package com.concretepage;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ThenApplyDemo1 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<String> cfuture =
CompletableFuture.supplyAsync(() -> "Krishna").thenApply(data -> "Shri "+ data);
String msg = cfuture.get();
System.out.println(msg);
}
}
输出
Shri Krishna
示例 2:
ThenApplyDemo2.java
package com.concretepage;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ThenApplyDemo2 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<String> cfuture =
CompletableFuture.supplyAsync(() -> computeArea(20, 30)).thenApply(data -> prettyPrint(data));
String msg = cfuture.get();
System.out.println(msg);
}
private static int computeArea(int a, int b) {
return a * b;
}
private static String prettyPrint(int area) {
return "Area: "+ area;
}
}
输出
Area: 600
示例 3:
ThenApplyDemo3.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class ThenApplyDemo3 {
public static void main(String[] args) throws InterruptedException {
List<Integer> list = Arrays.asList(10, 20, 30, 40);
list.stream().map(num -> CompletableFuture.supplyAsync(() -> num * num))
.map(cfuture -> cfuture.thenApply(res -> "Square: " + res)).map(t -> t.join())
.forEach(s -> System.out.println(s));
}
}
输出
Square: 100
Square: 400
Square: 900
Square: 1600
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.concretepage.com/java/java-8/java-completablefuture-thenapply
内容来源于网络,如有侵权,请联系作者删除!