gpt4 book ai didi

java - 从调用线程运行 CompletableFuture.thenAccept?

转载 作者:行者123 更新时间:2023-11-30 08:02:28 28 4
gpt4 key购买 nike

我想调用 CompletableFuture.supplyAsync() 将阻塞任务委托(delegate)给另一个线程。一旦该任务完成,我希望 CompletableFuture.thenAccept 消费者在调用线程的上下文中运行。

例如:

// Thread 1

CompletableFuture.supplyAsync(() -> {
// Thread 2

return BlockingMethod();
}).thenAccept((
Object r) -> {

// Thread 1
});

下面的代码表明CompletableFuture.thenAccept在它自己的线程中运行;可能与 CompletableFuture.supplyAsync 相同的池,因为我在运行它时获得相同的线程 ID:

System.out.println("Sync thread supply " + Thread.currentThread().getId());

CompletableFuture.supplyAsync(() -> {

System.out.println("Async thread " + Thread.currentThread().getId());

try {
Thread.sleep(2000);
}
catch (Exception e) {
e.printStackTrace();
}

return true;
}).thenAccept((
Boolean r) -> {

System.out.println("Sync thread consume " + Thread.currentThread().getId());
});

Thread.sleep(3000);

是否可以让 CompletableFuture.thenAccept 与调用线程同时运行?

最佳答案

CompletableFuture 只会执行你在 thenAccept 注册的 Consumer 当接收者 CompletableFuture (一个返回supplyAsync) 已完成,因为它需要完成时使用的值。

如果调用thenAccept 时接收方CompletableFuture 已完成,则Consumer 将在调用线程中执行。否则,它将在完成提交给 supplyAsyncSupplier 的任何线程上执行。

Is it possible to have CompletableFuture.thenAccept run concurrently with the calling thread?

这是一个令人困惑的问题,因为一个线程一次只能运行一件事。单个线程没有并发Concurrently 是一个跨越多个线程的属性。

如果您希望 Consumer 在调用 thenAccept 的同一线程上运行,则在 CompletableFuturejoin >,阻塞这个线程直到 future 完成。然后您可以自己执行 Consumer 或调用 thenAccept 为您执行它。

例如

CompletableFuture<Boolean> receiver = CompletableFuture.supplyAsync(() -> {
System.out.println("Async thread " + Thread.currentThread().getId());

try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}

return true;
});

receiver.join();
Consumer<Boolean> consumer = (Boolean r) -> {
System.out.println("Sync thread consume " + Thread.currentThread().getId());
};

consumer.accept(receiver.get());

(省略异常处理。)


如果您希望 Consumer 与提供给 supplyAsyncSupplier 并行运行,这是不可能的。 Consumer 旨在消费 Supplier 产生的值(value)。在 Supplier 完成之前,该值不可用。

关于java - 从调用线程运行 CompletableFuture.thenAccept?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36928012/

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