gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:40:31 26 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(由supplyAsync) 已完成,因为它需要完成时使用的值。

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

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

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

如果您希望 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 并行运行,这是不可能的。 消费者旨在消费供应商产生的值(value)。在Supplier完成之前该值不可用。

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

26 4 0