有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

创建内部时钟的时间Java

我希望从Java中的特定时间计算以毫秒为单位的时间

它的经典方法是使用System.currentTimeMillis();作为开始时间,然后再将其与前一个一起使用以获得经过的时间。我希望做类似的事情,但不依赖于系统时间

如果我依赖于系统时间,程序的用户可以操纵系统时钟来破解程序

我已尝试使用类似于以下内容的代码:

int elapsed = 0;
while (true) {
    Thread.sleep(10);
    elapsed += 10;
}

这是可行的,但我认为,如果电脑出现延迟,然后锁定一两秒钟,这就不太可靠了

有什么想法吗


共 (1) 个答案

  1. # 1 楼答案

    你想利用System.nanoTime。它与系统时钟无关。它只能用来追踪相对时间,而这似乎就是你想要做的

    为了避免这个答案只是另一个答案的链接,这里有一个简短的解释

    来自文件

    public static long nanoTime() Returns the current value of the most precise available system timer, in nanoseconds.

    This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

    还有一个指向计时器信息的链接:https://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks

    您可以使用Java的Timer类以特定的精度生成一个“check”回调,比如每500毫秒一次。此回调不会用于确定500毫秒是否确实通过。您可以在回调中调用System.nanoTime,并将其与上次调用System.nanoTime进行比较。无论挂钟如何变化,这都会给你一个相当准确的时间表示

    你可以看看这里:System.currentTimeMillis vs System.nanoTime