且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Thread.sleep的准确度如何?

更新时间:2023-02-26 20:04:25

Thread.sleep()是不准确的。不准确程度取决于底层操作系统及其计时器和调度程序。我经历过并行进行的垃圾收集会导致睡眠过度。

Thread.sleep() is inaccurate. How inaccurate depends on the underlying operating system and its timers and schedulers. I've experienced that garbage collection going on in parallel can lead to excessive sleep.

在进行实时模拟时,您必须纠正主循环,以确定 sleep 的不准确性。这可以通过计算唤醒的预期时间并将其与唤醒的实际时间进行比较并校正下一循环中的差异来完成。

When doing "real time" simulations you have to correct your main loop for the inaccuracies of sleep. This can be done by calculating the expected time of wake-up and comparing that to the actual time of wake-up and correcting for the difference in the next loop.

如果您需要更好的表现,请查看Java Real - 时间系统规范。我自己没有用过,所以我无法提供进一步的细节。

If you need better performance, have a look at the Java Real-Time System specification. I haven't used it myself so I can't provide further details.