gpt4 book ai didi

java - 如果在 runAsync 调用之后链接,thenRunAsync(相对于 thenRun)是否有任何区别?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:27 27 4
gpt4 key购买 nike

在下面的代码中,调用 thenRunAsync 有什么不同吗?我应该改为调用 thenRun 吗?

CompletableFuture.runAsync(this::doWork , executorService)
.thenRunAsync(this::handleSuccess);

针对评论的详细说明:如果我改为使用此代码,

CompletableFuture.runAsync(this::doWork , executorService)
.thenRun(this::handleSuccess);

它的行为会有什么不同吗?

在这两种情况下,行为都是非阻塞的,并且据我所知,第二个任务在第一个任务完成之前不会运行。

最佳答案

thenRun 方法允许在调用者线程中直接执行 Runnable,前提是 CompletableFuture 已经完成。因为即使在像 CompletableFuture.runAsync(…).thenRun(…); 这样的直接调用链中,异步任务也有可能在调用 thenRun 时已经完成,依赖操作有可能在调用者的线程中执行,这与 thenRunAsync 不同,后者将始终使用默认(或提供的)执行程序。

所以一句话,是的,它会产生影响。


顺便说一句,使用 thenRunAsync(单参数版本)不会使用提供给初始工厂调用的 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]

鉴于

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]

因此 thenRun 可以在调用者的线程或 Executor 的线程中执行操作,而单参数 thenRunAsync 将始终使用 Fork/Join 池,只有两个参数 thenRunAsync 将始终使用提供的执行程序。

关于java - 如果在 runAsync 调用之后链接,thenRunAsync(相对于 thenRun)是否有任何区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36462774/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com