Java completablefuture完整代码案例
时间: 2023-03-15 14:55:44 浏览: 79
CompletableFuture 是 Java 8 中引入的新特性,它是一个可以独立运行的 Future。它支持非阻塞的流式风格操作,并且可以和其他 CompletionStage 一起组合,构建复杂的流水线。下面是一个使用 CompletableFuture 来模拟耗时操作的完整代码案例: // 定义第一个耗时操作
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println("执行第一个耗时操作...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
});// 定义第二个耗时操作
CompletableFuture<String> completableFuture2 = completableFuture.thenApplyAsync(t -> {
System.out.println("执行第二个耗时操作...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return t + "2";
});// 定义第三个耗时操作
CompletableFuture<String> completableFuture3 = completableFuture2.thenApplyAsync(t -> {
System.out.println("执行第三个耗时操作...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return t + "3";
});// 获取结果
String result = completableFuture3.join();
System.out.println(result);
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)