首页 > 解决方案 > java中与延迟接口关联的getDelay(TimeUnit)

问题描述

要使用DelayQueue,我们需要为getDelay(TimeUnit unit)andcompareTo()方法实现Delayed接口,根据我的理解,getDelay方法将在参数TimeUnit枚举不固定的情况下被调用,它可能是TimeUnit.MICROSECONDSTimeUnit.NANOSECONDS等等TimeUnit.SECONDS。例如,如果unit.convert(long,TimeUnit.MICROSECONDS)使用我们要求将 MICROSECONDS 格式的长变量转换为 getDelay 调用者指定的变量。

unit.name()在下面的实现中使用过,但每次我只看到它打印TimeUnit.NANOSECONDS为什么它只打印 NANOSECONDS。它可以是任何东西。我已经测试了将近 7 个小时的代码以查看差异。谁能解释这种行为?

public long getDelay(TimeUnit unit){
    System.out.println("i'm calling "+unit.name());   // Always TimeUnit.NANOSECONDS
    long diff=millis-System.currentTimeMillis();
    return unit.convert(diff,TimeUnit.MILLISECONDS);  // Asking to convert to the one specified by the caller
}

标签: javaqueuedelayjava.util.concurrent

解决方案


一般来说,该接口可能就是这种情况,但它似乎DelayQueue只调用了类getDelay(TimeUnit.NANOSECONDS)

班上DelayQueue

当元素的 getDelay(TimeUnit.NANOSECONDS) 方法返回的值小于或等于零时,就会过期。

因此,它只会用 调用是有道理的TimeUnit.NANOSECONDS

其他类可以使用其他参数调用该方法。其他版本的 DelayQueue 也可能使用其他参数调用该方法,但您可以验证这个 openjdk8 实现没有。


推荐阅读