我想調用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
運行?