[英]Java how to timeout a thread WITHOUT using future.get and without blocking parent thread
[英]How to timeout a Future in Java without using Future.get() as it's a blocking operation?
我有一個期貨列表,我不斷循環檢查Future.isDone()
,如果是,那么我使用Future.get()
。 但是,有些情況下線程會永遠持續下去,為了避免這種情況,我想超時。
請幫助我在不使用Future.get()
作為阻塞操作的情況下對未來進行計時。 大多數關於 stackoverflow 超時的問題都指向Future.get()
,其中包含超時。
如果你可以使用CompletableFuture
而不是普通的Future
你可以使用CompletableFuture.anyOf()
方法:
返回一個新的 CompletableFuture,它在任何給定的 CompletableFuture 完成時完成,結果相同。
CompletableFuture<Void> combinedFuture =
CompletableFuture.anyOf(future1, future2, future3);
combinedFuture.get();
if (future1.isDone()) { ... }
if (future2.isDone()) { ... }
if (future3.isDone()) { ... }
在 Java 9 中,您有額外的方法來處理超時,例如CompletableFuture.completeOnTimeout()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.