java - System.currentTimeMillis 是否总是返回一个值 >= 以前的调用

https://docs.oracle.com/javase/6/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.

我不清楚我是否可以保证这段代码总是打印不断增加(或相同)的数字。

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

最佳答案

简短的回答是否定的,System.currentTimeMillis() 不是单调的。它基于系统时间,因此在时钟调整的情况下(例如通过 NTP)可能会受到任何一种方式(向前或向后)的影响。

System.nanoTime() 是单调的,当且仅当底层平台支持 CLOCK_MONOTONIC -- 参见 Java bug report 6458294 上的评论在某些情况下这是/不正确的情况下写得很好。

(另外,我个人观察到(多次)System.currentTimeMillis() 在没有时钟调整的情况下跨线程“向后”运行——也就是说,在一个线程中对该方法的调用返回的值低于在另一个线程中的调用,即使它在“实时”中按时间顺序发生)

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

关于java - System.currentTimeMillis 是否总是返回一个值 >= 以前的调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2978598/

相关文章:

c++ - 谁决定任何数据类型或结构的大小(取决于 32 位或 64 位)?

linux - Bash:WAITING超时

c - libc(glibc) 在我们的 linux 应用程序中的作用是什么?

c++ - 在 C、C++ 中检测 Windows 或 Linux

c++ - 在 Ubuntu 中学习 OpenGL

linux - 如何在不创建父目录的情况下使用 wget 镜像目录?

linux - 在类 Unix 系统中上次运行的 cron 作业的详细信息?

mysql - 你能推荐一个免费的 Linux 轻量级 MySQL GUI 吗?

linux - Home/End 键在 tmux 中不起作用

python - 从终端调用时使用默认 Python 而不是 Anaconda 安装