Java 中的 Timer 类如何对系统时钟敏感? [英] How is the Timer class in Java sensitive to the system clock?
问题描述
这个 关于 Timer
和 之间差异的高票答案
>ScheduledThreadPoolExecutor 在列举不同之处时提到了以下几点:
This highly voted answer on SO regarding the differences between a Timer
and a ScheduledThreadPoolExecutor
mentions the following while enumerating the differences:
定时器可以对系统时钟的变化敏感,ScheduledThreadPoolExecutor 不是.
Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't.
上述内容在《Java Concurrency in Practice》一书中逐字提及.
The above is mentioned verbatim inside the great book Java Concurrency in Practice.
我理解那个答案中提到的要点,除了上面提到的一点.Timers
可以对系统时钟敏感而 ScheduledThreadPoolExecutors
不是,这意味着什么?
I understand the points mentioned in that answer except the above mentioned one. What does it mean to say that Timers
can be sensitive to system clock whereas ScheduledThreadPoolExecutors
are not?
推荐答案
Timer
使用 System.currentTimeMillis()
,表示挂钟时间 并且永远不应该用于检查相对时间,例如确定某事运行需要多长时间,或者在这种情况下,在执行任务之前延迟多长时间.System.currentTimeMillis()
受系统时钟自动调整甚至手动更改系统时钟等因素的影响.因此,如果你调用它两次并检查你得到的次数之间的差异,你甚至可以得到一个负数.
Timer
uses System.currentTimeMillis()
, which represents wall clock time and should never be used for checking relative times such as determining how long something took to run or, in this case, how long to delay before executing a task. System.currentTimeMillis()
is affected by things like automatic adjustments to the system clock or even manually changing the system clock. As such, if you call it twice and check the difference between the times you get, you can even get a negative number.
System.nanoTime()
另一方面,专门用于测量经过的时间,并且应该用于此类事情.
System.nanoTime()
, on the other hand, is specifically intended for measuring elapsed time and is what should be used for this sort of thing.
这篇关于Java 中的 Timer 类如何对系统时钟敏感?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!