欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 八卦 > Java CompletableFuture

Java CompletableFuture

2025/4/19 19:58:05 来源:https://blog.csdn.net/weixin_47363690/article/details/143248090  浏览:    关键词: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);

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词