You need to enable JavaScript to run this app. 为什么CompletableFuture的回调方法未按照预期顺序执行?
优惠活动
大模型
产品
解决方案
定价
更多

为什么CompletableFuture的回调方法未按照预期顺序执行?

目标

理解CompletableFuture的工作原理。

预期执行逻辑

我最初认为CompletableFuture.runAsync().thenRun().thenRunAsync()的链式调用,会严格按照runAsync() -> thenRun() -> thenRunAsync()的顺序依次执行。

实际运行表现

运行时出现竞态条件,执行顺序不固定,常见的两种执行顺序如下:

  • runAsync -> thenRunAsync+e -> 后续任务
  • runAsync -> thenRun -> 后续任务
问题复现代码
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.LockSupport;

public class RunExample5 {
    public static void main(String[] args) {
        ExecutorService e = Executors.newSingleThreadExecutor(r -> new Thread(r, "sole thread"));
        CompletableFuture<?> f = CompletableFuture.runAsync(() -> {
            System.out.println("runAsync:\t" + Thread.currentThread());
            LockSupport.parkNanos((int) 1e9);
        }, e);
        f.thenRun(() -> System.out.println("thenRun:\t" + Thread.currentThread()));
        f.thenRunAsync(() -> System.out.println("thenRunAsync:\t" + Thread.currentThread()));
        f.thenRunAsync(() -> System.out.println("thenRunAsync+e:\t" + Thread.currentThread()), e);
        LockSupport.parkNanos((int) 2e9);
        e.shutdown();
    }
}
问题原因

你看到的执行顺序混乱是回调注册方式错误导致的,和CompletableFuture的回调调度规则一致,不属于异常现象:

  1. 所有回调都是独立绑定到根实例f上的,并不是串联关系
    你写的f.thenRun、f.thenRunAsync都是直接绑定到f的完成事件上,当f运行结束后,所有已经注册的回调会同时触发,相互之间没有先后依赖,自然不会按你预想的顺序执行。只有写成f.thenRun(...).thenRunAsync(...)的链式结构,让下一个回调绑定在上一个回调的返回CompletableFuture上,才能保证执行顺序。
  2. 不同回调的调度逻辑不同
  • thenRun:如果注册时f已经完成,直接在当前注册线程(也就是main线程)执行;如果f还没完成,会在f的执行线程上运行
  • 无自定义线程池的thenRunAsync:不管f是否完成,都会把任务提交到JDK默认的公共ForkJoinPool执行
  • 带自定义线程池的thenRunAsync+e:不管f是否完成,都会把任务提交到你传入的单线程池执行
    你用的是单线程自定义池,runAsync和thenRunAsync+e都提交到这个池子里排队,其他回调走不同的线程调度,自然就会出现执行顺序不固定的竞态情况。

内容的提问来源于stack exchange,提问作者Jason Rich Darmawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 12:57:02