线程异步编排并行(CompletableFuture)

本文详细介绍了如何使用Java的CompletableFuture进行线程异步编排,包括两个任务组合(runAfterBoth、thenAcceptBoth、thenCombine)和任意任务完成后的处理(runAfterEither、acceptEither、applyToEither),以及多任务组合(allOf、anyOf)的示例应用,展示了如何在多线程环境下高效地组织并发任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

美图

在这里插入图片描述

两个任务组合(一)

任务一和任务二都处理完成之后,才能处理任务三

runAfterBoth

组合两个future,不需要获取future的结果,只需要两个future处理完成后,处理该任务,无返回结果

CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action)
CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor)
示例
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> System.out.println("任务1"));
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> System.out.println("任务2"));
future1.runAfterBoth(future2, () -> System.out.println("任务3"));

thenAcceptBoth

组合两个future,需要获取future的结果,只需要两个future处理完成后,处理该任务,无返回结果

CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action)
CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action)
CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action, Executor executor)
示例
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
   
    System.out.println("任务1");
    return 10;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
   
    System.out.println("任务2");
    return 20;
});
future1.thenAcceptBoth(future2, (res1, res2) -> {
   
    System.out.println(<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值