有谁知道一个库,它为 Java 提供了一个错误不高于 1-2 毫秒的 Thread.sleep()?
我尝试了 sleep 、错误测量和 BusyWait 的混合,但在不同的 Windows 机器上我没有得到可靠的结果。
如果实现也适用于 Linux 和 MacOS,它可以是 native 实现。
编辑 Nick 提供的链接 (http://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks) 是一个非常好的资源,可以帮助您了解 Java 中各种计时器/ sleep /时钟的问题。
最佳答案
要提高 sleep 粒度,您可以尝试以下 Thread.sleep页面。
Bugs with Thread.sleep() under Windows
If timing is crucial to your application, then an inelegant but practical way to get round these bugs is to leave a daemon thread running throughout the duration of your application that simply sleeps for a large prime number of milliseconds (Long.MAX_VALUE will do). This way, the interrupt period will be set once per invocation of your application, minimising the effect on the system clock, and setting the sleep granularity to 1ms even where the default interrupt period isn't 15ms.
该页面还提到它会导致系统范围内的 Windows 更改,这可能会导致用户的时钟由于这个 bug 而快速运行。 .
编辑
提供有关此的更多信息 here和相关的 bug report来自太阳。
关于java - Windows 上的 Java 准确 sleep ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/824110/