登录
首页 >  文章 >  java教程

CompletableFuture并发编程实战教程

时间:2026-01-31 16:59:36 394浏览 收藏

有志者,事竟成!如果你在学习文章,那么本文《CompletableFuture并发编程使用详解》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

CompletableFuture 提供非阻塞异步编程能力,支持链式调用组合任务。1. 用 runAsync/supplyAsync 创建异步任务,可指定线程池;2. thenApply/thenAccept/thenRun 实现结果处理;3. thenCompose 串行组合任务,thenCombine 并行合并结果;4. exceptionally/handle 进行异常处理;5. allOf/anyOf 协调多个任务同步。合理使用可提升代码可读性与健壮性,适用于 I/O 密集型场景。

Java并发编程中CompletableFuture使用方法

在Java并发编程中,CompletableFuture 是对 Future 的增强,提供了非阻塞、函数式、可编排的异步编程能力。它允许你以链式调用的方式组合多个异步任务,避免回调地狱,提升代码可读性和维护性。

1. 创建 CompletableFuture 任务

你可以通过静态方法创建一个异步任务:

  • runAsync():执行无返回值的任务
  • supplyAsync():执行有返回值的任务

默认使用 ForkJoinPool.commonPool() 线程池,也可以传入自定义线程池:

CompletableFuture<void> run = CompletableFuture.runAsync(() -> {
    System.out.println("执行无返回任务");
});
<p>CompletableFuture<string> supply = CompletableFuture.supplyAsync(() -> {
return "Hello from async";
}, Executors.newFixedThreadPool(2));</string></p></void>

2. 任务完成后处理结果(thenApply, thenAccept, thenRun)

当异步任务完成时,可以进行后续操作:

  • thenApply(Function):转换结果并返回新值
  • thenAccept(Consumer):消费结果,无返回
  • thenRun(Runnable):不关心结果,只运行后续逻辑
CompletableFuture<string> future = CompletableFuture.supplyAsync(() -> "Hi");
<p>future.thenApply(s -> s + " World")
.thenAccept(System.out::println)
.thenRun(() -> System.out.println("完成"));</p></string>

3. 组合多个异步任务(thenCompose, thenCombine)

当你需要合并多个异步操作时,这两个方法非常有用:

  • thenCompose:串行组合,前一个任务的结果用于下一个任务(类似 flatMap)
  • thenCombine:并行组合,两个任务都完成后合并结果
// 串行:先获取用户,再获取订单
CompletableFuture<user> getUser = CompletableFuture.supplyAsync(() -> new User("Alice"));
CompletableFuture<order> getOrder = getUser.thenCompose(user ->
    CompletableFuture.supplyAsync(() -> new Order(user.getName()))
);
<p>// 并行:同时获取价格和折扣,然后合并
CompletableFuture<double> price = CompletableFuture.supplyAsync(() -> 100.0);
CompletableFuture<double> discount = CompletableFuture.supplyAsync(() -> 0.9);
CompletableFuture<double> finalPrice = price.thenCombine(discount, (p, d) -> p * d);</double></double></double></p></order></user>

4. 异常处理(handle, exceptionally)

异步任务可能出错,CompletableFuture 提供了异常处理机制:

  • exceptionally(Function):仅处理异常,返回默认值
  • handle(BiFunction):无论是否异常都会执行,可统一处理结果和异常
CompletableFuture<string> broken = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("出错了");
});
<p>broken.exceptionally(ex -> "默认值")
.thenAccept(System.out::println);</p><p>// 或者用 handle
broken.handle((result, ex) -> {
if (ex != null) {
System.out.println("捕获异常: " + ex.getMessage());
return "恢复结果";
}
return result;
});</p></string>

5. 等待多个任务完成(allOf, anyOf)

当你需要协调多个异步任务时:

  • CompletableFuture.allOf(...):所有任务都完成才算完成,返回 void
  • CompletableFuture.anyOf(...):任意一个完成即完成
CompletableFuture<string> f1 = CompletableFuture.supplyAsync(() -> "A");
CompletableFuture<string> f2 = CompletableFuture.supplyAsync(() -> "B");
CompletableFuture<string> f3 = CompletableFuture.supplyAsync(() -> "C");
<p>CompletableFuture<void> all = CompletableFuture.allOf(f1, f2, f3);
all.thenRun(() -> {
System.out.println("全部完成");
try {
System.out.println(f1.get()); // 获取结果
} catch (Exception e) { }
});</void></p></string></string></string>

基本上就这些核心用法。合理使用 CompletableFuture 能让你的异步代码更清晰、更健壮,尤其适合 I/O 密集型或远程调用场景。关键是理解每个方法的返回类型和执行时机,避免阻塞主线程。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>