我想调用CompletableFuture.supplyAsync()
将阻塞任务委托给另一个线程。一旦完成任务,我希望CompletableFuture.thenAccept
使用者在调用线程的上下文中运行。从调用线程运行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
运行?