我的目标是了解 CompletableFuture 的工作原理。
我的预期结果:如果我执行CompletableFuture.runAsync().thenRun().thenRunAsync()
。线程将按照runAsync() -> thenRun() -> thenRunAsync()
的顺序执行。
我的实际结果:序列是竞争条件。有时:
runAsync
->thenRunAsync+e
-> ...runAsync
->thenRun
-> ...
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
本身并不跟踪对 thenRun
或 thenRunAsync
的每次调用并按顺序运行它们;相反,一旦主要工作完成,它就会将 thenRun
或 thenRunAsync
中的所有内容视为可同时运行。如果您想链接更复杂的工作序列,则需要使用 thenRun
或 thenRunAsync
的返回值 - 一个 CompletionStage
对象 -并对其调用 thenRunAsync
。
关于java - 为什么CompletableFuture没有按顺序执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68741728/