Java11优雅实现在一段时间内等待某个结果

2020-12-31 861点热度 0人点赞 0条评论

比如有个需求,超时30秒,检查是否准备好,某个条件是否为真,30秒后也算条件为假,比较传统的做法是,每一秒检查,中间用Thread.sleep停一下

boolean checkResult = false;
for (int i = 0; i < 30; i++) {
    if (condition()) {//某种条件下判断为真,表示已经准备好
         checkResult = true;
          break;
    }
    Thread.sleep(1000L);
}
System.out.println(checkResult);

这样不是很优雅,且容易阻塞线程

Java8以上可以利用CompletableFuture还有CountDownLatch来实现

利用CompletableFutures实现耗时操作的检查
private void test() throws Exception {
   CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(this::condition)
                .completeOnTimeout(false, 30, TimeUnit.SECONDS);
   System.out.println(future.get());
}

public boolean condition() {
   //这里是比较耗时的操作,可能30秒内不返回
   return true;
}
利用CountDownLatch来实现,新建LimitedTimeCondition.java
public class LimitedTimeCondition {
    private final CountDownLatch conditionMetLatch;
    private final Integer timeoutSeconds;

    public LimitedTimeCondition(final Integer timeoutSeconds) {
        conditionMetLatch = new CountDownLatch(1);
        this.timeoutSeconds = timeoutSeconds;
    }

    public boolean waitForConditionToBeMet() {
        try {
            return conditionMetLatch.await(timeoutSeconds, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
            //被打断了
            return false;
        }
    }

    public void conditionWasMet() {
        conditionMetLatch.countDown();
    }

}
如何使用
LimitedTimeCondition condition = new LimitedTimeCondition(30);
//在其他方法,适当的时候,调用condition.conditionWasMet();
if (condition.waitForConditionToBeMet()) {
//成功
} else {
//30秒超时不成功
}

 

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论