[英]Calling ExecutorService.shutdownNow from CompletableFuture
[英]CompletableFuture from ExecutorService
我創建了一個自定義的ExecutorService
ExecutorService executor =
new ThreadPoolExecutor(0, maxPoolSize, keepAliveTime, timeUnit,
new LinkedBlockingDeque<>());
我向其提交任務
Future<String> result = executor.submit(() -> "test");
如您所見,執行程序返回一個微薄的Future
; 我更希望有一個CompletableFuture
可以與其他CompletableFuture
。
在Guava 中,我們有ListeningExecutorService
返回ListenableFuture
s 。 就我的意圖和目的而言,那些ListenableFuture
和CompletableFuture
一樣好。
盡管如此,我還是想盡可能多地使用 Java 的標准庫,這意味着我正在尋找一種方法來從我的自定義執行程序中獲取CompletableFuture
。
事后看來很明顯:不要嘗試從 executor 獲取CompletableFuture
,而是將 executor 傳遞給CompletableFuture
。
像這樣:
CompletableFuture<String> futureOutput =
CompletableFuture.supplyAsync(() -> "test", executor);
任務將使用executor
提供的線程之一executor
,客戶端可以使用CompletableFuture
所有便利來獲取任務的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.