温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java多线程怎样用completablefuture

发布时间:2026-10-24 00:20:00 来源:亿速云 阅读:94 作者:小樊 栏目:编程语言

在 Java 中,CompletableFuture 是 Java 8 引入的用于异步编程和多线程任务编排的工具,比传统的 Thread / ExecutorService + Future 更灵活。

下面从基本用法 → 常用方法 → 实战示例逐步说明。


一、最基础的用法(异步执行任务)

1️⃣ 异步执行,不关心返回值

CompletableFuture.runAsync(() -> {
    System.out.println("异步任务执行:" + Thread.currentThread().getName());
});

2️⃣ 异步执行,有返回值

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    return "hello";
});

System.out.println(future.join()); // 阻塞获取结果

join() 会阻塞当前线程
get() 会抛受检异常


二、使用自定义线程池(推荐)

默认使用 ForkJoinPool.commonPool(),生产环境建议自定义:

ExecutorService executor = Executors.newFixedThreadPool(4);

CompletableFuture.supplyAsync(() -> "task", executor);

三、任务编排(重点)

1️⃣ thenApply(有返回值,串行)

CompletableFuture<Integer> future =
    CompletableFuture.supplyAsync(() -> 10)
        .thenApply(x -> x + 5);

System.out.println(future.join()); // 15

2️⃣ thenAccept(无返回值,串行)

CompletableFuture.supplyAsync(() -> "done")
    .thenAccept(System.out::println);

3️⃣ thenRun(不关心结果)

CompletableFuture.supplyAsync(() -> 1)
    .thenRun(() -> System.out.println("完成"));

4️⃣ 异步回调(thenApplyAsync)

.thenApplyAsync(x -> x * 2, executor);

四、多个 Future 组合

1️⃣ thenCompose(依赖前一个结果)

CompletableFuture<Integer> f = CompletableFuture
    .supplyAsync(() -> 10)
    .thenCompose(x -> CompletableFuture.supplyAsync(() -> x * 2));

System.out.println(f.join()); // 20

2️⃣ thenCombine(两个任务并行,结果合并)

CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 1);
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 2);

CompletableFuture<Integer> result =
    f1.thenCombine(f2, (a, b) -> a + b);

System.out.println(result.join()); // 3

3️⃣ allOf(等待所有任务完成)

CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2);

all.join();
System.out.println("全部完成");

4️⃣ anyOf(任意一个完成)

CompletableFuture<Object> any = CompletableFuture.anyOf(f1, f2);

五、异常处理

1️⃣ exceptionally

CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("error");
}).exceptionally(ex -> {
    System.out.println(ex.getMessage());
    return "default";
});

2️⃣ handle(无论成功失败)

.handle((res, ex) -> {
    if (ex != null) return "fallback";
    return res;
});

六、完整实战示例(推荐写法)

ExecutorService executor = Executors.newFixedThreadPool(4);

CompletableFuture<String> future =
    CompletableFuture.supplyAsync(() -> "A", executor)
        .thenApplyAsync(s -> s + "B", executor)
        .thenApplyAsync(s -> s + "C", executor)
        .exceptionally(ex -> "ERROR");

System.out.println(future.join());

七、使用建议

✅ 使用自定义线程池
✅ 避免 join()/get() 滥用
✅ 复杂流程用 thenCompose / thenCombine
✅ 一定要处理异常


如果你有具体业务场景(比如:并发调用接口、批量处理、限流、超时控制),我可以直接给你对应代码。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手