java-如何处理System.nanoTime()在两次调用之间返回相同的值?
此问题无意于对System.nanoTime()的攻击.我意识到,正确使用它是一种非常棘手的方法.

有什么方法可以处理System.nanoTime()在两次调用之间返回相同值的情况?示例:多个线程调用System.nanoTime()并获得相同的值.

在Windows上运行测试时,我经常在代码库中看到这种情况,这让我感到惊讶.我们使用nanoTime对通过多个线程到达的事件进行排序.也许这只是Windows的问题,而Linux单调时钟更细.

参考文献:

> Is System.nanoTime() guaranteed to return unique values?
> Is System.nanoTime() completely useless?

最佳答案
为了解释为什么获得相同的价值,请仔细阅读文档:

This method provides nanosecond precision, but not necessarily
nanosecond resolution (that is, how frequently the value changes) – no
guarantees are made except that the resolution is at least as good as
that of currentTimeMillis().

您的计算机可能没有足够的时钟分辨率,因此nanoTime可能会在相当长的时间内返回相同的数字.

至于你的问题

What are some ways to deal with System.nanoTime() returning the same
value between calls?

我建议使用某种atomic counter,如Claudio Corsi建议的那样.

点击查看更多相关文章

转载注明原文:java-如何处理System.nanoTime()在两次调用之间返回相同的值? - 乐贴网