有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中超时Future而不使用Future。get()是阻塞操作吗?

我有一个期货清单,我不断循环检查Future.isDone(),如果是,那么我使用Future.get()。但是,在有些情况下,线程会一直持续下去,为了避免这种情况,我想暂停

请帮助我在不使用Future.get()作为阻塞操作的情况下为未来计时。这里关于stackoverflow超时的大多数问题都指向Future.get(),其中有一个超时


共 (1) 个答案

  1. # 1 楼答案

    如果可以使用^{}而不是普通的Future,那么可以使用CompletableFuture.anyOf()方法:

    Returns a new CompletableFuture that is completed when any of the given CompletableFutures complete, with the same result.

    CompletableFuture<Void> combinedFuture = 
        CompletableFuture.anyOf(future1, future2, future3); 
    combinedFuture.get();
    
    if (future1.isDone()) { ... }
    if (future2.isDone()) { ... }
    if (future3.isDone()) { ... }
    

    在Java 9中,有额外的方法来处理超时,例如^{}