方法thenRun
允许执行Runnable
直接在调用者的线程中,如果CompletableFuture
已经完成了。因为即使在像这样的直接调用链中CompletableFuture.runAsync(…).thenRun(…);
此时异步任务有可能已经完成thenRun
被调用时,依赖操作有可能在调用者的线程中执行,这与thenRunAsync
它将始终使用默认(或提供的)执行器。
所以用一句话来说,是的,这会有所不同。
顺便说一下,使用thenRunAsync
(单参数版本)不会使用Executor
提供给初始工厂调用,但默认Executor
.
您可以轻松比较不同的行为:
public static void main(String[] args) {
ExecutorService e=Executors.newSingleThreadExecutor(r -> new Thread(r, "sole thread"));
CompletableFuture<?> f=CompletableFuture.runAsync(()->{}, e);
f.join();
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);
e.shutdown();
}
将打印
thenRun: Thread[main,5,main]
thenRunAsync: Thread[ForkJoinPool.commonPool-worker-1,5,main]
thenRunAsync+e: Thread[sole thread,5,main]
whereas
public static void main(String[] args) {
ExecutorService e=Executors.newSingleThreadExecutor(r -> new Thread(r, "sole thread"));
CompletableFuture<?>f=CompletableFuture.runAsync(()->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();
}
将打印
thenRun: Thread[sole thread,5,main]
thenRunAsync: Thread[ForkJoinPool.commonPool-worker-1,5,main]
thenRunAsync+e: Thread[sole thread,5,main]
So thenRun
可以在调用者的线程或Executor
的线程,而单一参数thenRunAsync
将始终使用 Fork/Join 池并且仅使用两个参数thenRunAsync
将始终使用提供的执行器。