System.currentTimeMillis是否总是返回值> =以前的调用?

编程入门 行业动态 更新时间:2024-10-25 21:15:28
本文介绍了System.currentTimeMillis是否总是返回值> =以前的调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

http:// java.sun/j2se/1.4.2/docs/api/java/lang/System.html#currentTimeMillis()说:

以毫秒为单位返回当前时间。请注意,虽然返回值的时间单位是毫秒,但值的粒度取决于底层操作系统,并且可能更大。例如,许多操作系统以几十毫秒为单位测量时间。

Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

我不清楚我是否能保证这一点代码将始终打印不断增加(或相同)的数字。

It is not clear to me if I am guaranteed that this code will always print ever increasing (or the same) numbers.

while (1) { System.out.println(System.currentTimeMillis() ); }

推荐答案

简短的回答是否定的, System.currentTimeMillis() 不单调。它基于系统时间,因此在时钟调整的情况下可以以任何方式(向前或向后)进行变化(例如,通过 NTP )。

The short answer is no, System.currentTimeMillis() is not monotonic. It is based on system time, and hence can be subject to variation either way (forward or backward) in the case of clock adjustments (e.g. via NTP).

System.nanoTime()是单调的,如果和仅当底层平台支持 CLOCK_MONOTONIC 时 - 请参阅 Java错误报告6458294 ,以便在某些情况下进行良好的写入,这是不正确的。

System.nanoTime() is monotonic, if and only if the underlying platform supports CLOCK_MONOTONIC -- see the comments on Java bug report 6458294 for a good writeup on some circumstances where this is/isn't true.

(并且,as一个额外的轶事,我个人观察(几次) System.currentTimeMillis()在没有时钟调整的情况下,跨线程运行'向后' - 即a在一个线程中调用该方法返回的值低于另一个线程中的调用值,即使它在实时之后按时间顺序发生)

(And, as an additional anecdote, I have personally observed (several times) System.currentTimeMillis() run 'backwards', in the absence of clock adjustments, across threads -- that is, a call to that method in one thread returned a lower value than a call in another thread, even though it occurred chronologically after it in 'real-time')

如果需要单调的酸味ce,支持单调性的平台上的System.nanoTime()是您的最佳选择。

If you need a monotonic source, System.nanoTime() on a platform supporting monotonicity is your best option.

更多推荐

System.currentTimeMillis是否总是返回值> =以前的调用?

本文发布于:2023-10-19 19:21:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508518.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   currentTimeMillis   System   amp   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!