System.currentTimeMillis是否总是返回值> =以前的调用? [英] Will System.currentTimeMillis always return a value >= previous calls?

查看:194
本文介绍了System.currentTimeMillis是否总是返回值> =以前的调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http:// java.sun.com/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是否总是返回值> =以前的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆