java - java中与延迟接口关联的getDelay(TimeUnit)
问题描述
要使用DelayQueue,我们需要为getDelay(TimeUnit unit)
andcompareTo()
方法实现Delayed接口,根据我的理解,getDelay方法将在参数TimeUnit枚举不固定的情况下被调用,它可能是TimeUnit.MICROSECONDS
,TimeUnit.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
}
解决方案
一般来说,该接口可能就是这种情况,但它似乎DelayQueue
只调用了类getDelay(TimeUnit.NANOSECONDS)
。
班上DelayQueue
说
当元素的 getDelay(TimeUnit.NANOSECONDS) 方法返回的值小于或等于零时,就会过期。
因此,它只会用 调用是有道理的TimeUnit.NANOSECONDS
。
其他类可以使用其他参数调用该方法。其他版本的 DelayQueue 也可能使用其他参数调用该方法,但您可以验证这个 openjdk8 实现没有。
推荐阅读
- list - Power Query - 无间隙旋转
- c# - WPF InitializeComponent 无法识别
- string - 字符串词库:因为很多不同的起始字符,需要用不等于逻辑的Split
- android - 不使用 Firebase 的简单颤振应用在启动时会出现 Firebase 错误
- python - 尝试将我的 keras 模型导出到 tensorflow 服务时出现错误
- c# - C#:与内联代码相比,这如何通过多个函数更快地执行?
- jenkins - SonarQube 扫描仪在 Jenkins 作业中执行后未将结果发送到 SonarQube
- php - 如何使用summernote通过ajax同时传递内容和图片
- html - 在不使用类或 ID 的情况下选择 div 中的 div
- c# - 使用 Firebase 数据库处理事务和数组