Clock.systemUTC()
文档说此方法可能使用 System.currentTimeMillis()
或更高分辨率的时钟(如果可用)。那么System.currentTimeMillis()
使用什么时钟呢?这两个值的粒度有区别吗?
最佳答案
Can there be a difference in the granularity of these two values?
Clock
类有 2 个用于检索当前时间的方法:
因为 instant()
返回 Instant
,它可以以纳秒的精度表示时间,答案是显而易见的。
答案:是的。
What clock does System.currentTimeMillis() use then?
如果你查看Clock.systemUTC()
的源代码,你会发现它使用了一个内部SystemClock
类。在 millis()
方法的注释中,它说(引用 Java 15):
System.currentTimeMillis()
andVM.getNanoTimeAdjustment(offset)
use the same time source -System.currentTimeMillis()
simply limits the resolution to milliseconds.
So we take the faster path and callSystem.currentTimeMillis()
directly - in order to avoid the performance penalty ofVM.getNanoTimeAdjustment(offset)
which is less efficient.
答案: System.currentTimeMillis()
和 Clock.instant()
使用相同的时间源。
关于java - 黑白 Clock.systemUTC() 和 System.currentTimeMillis() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65754746/