当前位置: 首页 > news >正文

Java CompletableFuture

目录

1 基本概念

2 创建 CompletableFuture

2.1 已完成或已知结果

2.2 运行异步任务

2.2.1 runAsync

2.2.2 supplyAsync

3 完成处理 

3.1 thenApply

3.2 thenAccept

3.3 thenRun

3.4 thenCompose

4 异常处理

4.1 exceptionally

4.2 handle

5 组合多个 CompletableFuture

5.1 thenCombine

5.2 allOf

5.3 anyOf


CompletableFuture 是 Java 8 引入的一个类,它实现了 FutureCompletionStage 接口。CompletableFuture 提供了一种非阻塞的方式处理异步计算的结果,并且可以方便地构建复杂的异步操作链。它可以用来表示一个异步计算的结果,这个结果可能还没有完成,但是最终会完成或者异常终止。

1 基本概念

  • Future:代表一个异步计算的结果。
  • CompletionStage:代表异步计算过程中的某个阶段,可以在这个阶段上添加依赖关系,比如当一个阶段完成后执行另一个阶段。
  • CompletableFuture:是 Future 的一个实现,除了基本的 Future 操作外,还提供了丰富的 API 来组合多个异步操作。

2 创建 CompletableFuture

2.1 已完成或已知结果

当你已经知道计算的结果时,可以使用 completedFuture 方法来立即创建一个已完成的 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("Hello, World!");
2.2 运行异步任务
2.2.1 runAsync

执行不返回结果的操作。

CompletableFuture<Void> runFuture = CompletableFuture.runAsync(() -> {System.out.println("Running an async task without result.");
});
2.2.2 supplyAsync

执行有返回结果的操作。

CompletableFuture<String> supplyFuture = CompletableFuture.supplyAsync(() -> {return "Result from async computation";
});

 注意:这两个方法都有一个重载版本接受 Executor 参数,允许你指定用于执行异步任务的线程池。

3 完成处理 

CompletableFuture 的结果可用时,可以通过以下方法来处理结果:

3.1 thenApply

CompletableFuture 的结果应用函数并返回一个新的 CompletableFuture

CompletableFuture<Integer> cf = CompletableFuture.supplyAsync(() -> 10).thenApply(x -> x * 2); // 结果变为 20
3.2 thenAccept

仅消费 CompletableFuture 的结果而不产生新的结果。

CompletableFuture.supplyAsync(() -> "Result").thenAccept(result -> System.out.println("Received: " + result));
3.3 thenRun

CompletableFuture 完成后运行一段代码,这段代码既不需要输入也不产生输出。

CompletableFuture.supplyAsync(() -> "Some value").thenRun(() -> System.out.println("Task is done"));
3.4 thenCompose

将当前 CompletableFuture 的结果作为参数传递给另一个函数,并返回该函数产生的 CompletableFuture

CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> "prefix_").thenCompose(prefix -> CompletableFuture.supplyAsync(() -> prefix + "suffix"));

4 异常处理

4.1 exceptionally

CompletableFuture 抛出异常时,提供一个替代的结果或者恢复逻辑。

CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {if (/* some condition */) throw new RuntimeException("Error occurred");return "Result";
}).exceptionally(ex -> {System.out.println("Caught exception: " + ex.getMessage());return "Default Result"; // 返回默认值
});
4.2 handle

同时处理正常的结果和异常情况。

CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {if (/* some condition */) throw new RuntimeException("Error occurred");return "Result";
}).handle((result, ex) -> {if (ex != null) {System.out.println("Exception occurred: " + ex.getMessage());return "Fallback Result";} else {return result;}
});

5 组合多个 CompletableFuture

5.1 thenCombine

等待两个 CompletableFuture 都完成,并结合它们的结果。

CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 20);CompletableFuture<Integer> combined = f1.thenCombine(f2, (a, b) -> a + b);
5.2 allOf

等待所有给定的 CompletableFuture 完成。

List<CompletableFuture<?>> futures = Arrays.asList(CompletableFuture.runAsync(() -> {/* do something */}),CompletableFuture.runAsync(() -> {/* do something else */})
);CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenRun(() -> System.out.println("All tasks are completed"));
5.3 anyOf

等待任意一个给定的 CompletableFuture 完成。

List<CompletableFuture<String>> futures = Arrays.asList(CompletableFuture.supplyAsync(() -> "First"),CompletableFuture.supplyAsync(() -> "Second")
);CompletableFuture<Object> firstToComplete = CompletableFuture.anyOf(futures.toArray(new CompletableFuture[0]));
firstToComplete.thenAccept(System.out::println);


http://www.mrgr.cn/news/58900.html

相关文章:

  • git bisect和git blame
  • vue使用rem适配各种分辨率设备
  • 03.04、化栈为队
  • react18中的jsx 底层渲染机制相关原理
  • vue3+ElementPlus+Table+Fixed属性导致行背景颜色失效
  • OpenFace安装教程及踩坑记录 (Ubuntu20.04—2024.10.24)
  • 计算机网络——开放系统互连参考模型
  • Spring Boot框架下的厨艺社区开发
  • 解决微信OAuth2.0网页授权回调域名只能设置一个的问题
  • Docker部署项目
  • LeetCode 每日一题 2024/10/21-2024/10/27
  • day02|计算机网络重难点之HTTP请求报文和响应报文、HTTP的请求方式(方法字段)、GET请求和POST请求的区别
  • 统一异常处理和拦截器
  • 了解Oracle表结构查询:获取列信息与注释
  • Mac打开环境变量配置文件,source ~/.zshrc无法打开问题解决
  • 分享一款录屏、直播软件
  • 计算机组成原理之指令系统的基本概念、指令格式
  • 数学之三角函数
  • 太香了,用AI做育儿账号带货,卖出2.1万件赚佣金10W+
  • Spring Boot框架下的厨艺社交网络构建
  • IP协议详解:报头格式、主机定位、转发流程、网段划分与路由机制
  • 算法刷题-小猫爬山
  • 《打造 C++团队知识库:提升团队实力,开启高效编程之旅》
  • 函数递归
  • 嵌入式软开——八股文——学习引导和资料网址
  • 【微服务】Java 对接飞书多维表格使用详解