java - 为什么CompletableFuture没有按顺序执行?

标签 java completable-future

我的目标是了解 CompletableFuture 的工作原理。

我的预期结果:如果我执行CompletableFuture.runAsync().thenRun().thenRunAsync()。线程将按照runAsync() -> thenRun() -> thenRunAsync()的顺序执行。

我的实际结果:序列是竞争条件。有时:

  1. runAsync -> thenRunAsync+e -> ...
  2. runAsync -> thenRun -> ...

Reference from SO

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();
  }
}

最佳答案

你需要

f.thenRun(() -> System.out.println("thenRun:\t" + Thread.currentThread()))
    .thenRunAsync(() -> System.out.println("thenRunAsync:\t" + Thread.currentThread()))
    .thenRunAsync(() -> System.out.println("thenRunAsync+e:\t" + Thread.currentThread()), e);

CompletableFuture 的接口(interface)并不像您想象的那样工作。 f 本身并不跟踪对 thenRunthenRunAsync 的每次调用并按顺序运行它们;相反,一旦主要工作完成,它就会将 thenRunthenRunAsync 中的所有内容视为可同时运行。如果您想链接更复杂的工作序列,则需要使用 thenRunthenRunAsync 的返回值 - 一个 CompletionStage 对象 -并对其调用 thenRunAsync

关于java - 为什么CompletableFuture没有按顺序执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68741728/

相关文章:

java - 使用 onItemClickListener 单击时,从数据库获取的 gridview 中的图像未全屏显示

Java - 为什么 jpanel 的大小不起作用

java - 如何在 CompletableFuture 完成后通过垃圾收集进行回收?

java - 如何在 CompletableFutures 中收集成功和错误?

java - 从阻塞方法调用创建 CompletableFuture

java priorityQueue更新问题

java - 为什么 minHeight 属性在 WebView Android 中不起作用?

java - 在 Java 中,如何从重写类的实例调用重写类的方法

java - 当我执行 get 并抛出异常时,CompletableFuture 会自动取消吗?

java - 在 Java 8/11 中是否可以组合 2 个以上的 CompletableFuture?