Windows上的Java准确睡眠 [英] Accurate Sleep for Java on Windows

查看:188
本文介绍了Windows上的Java准确睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道为Java提供Thread.sleep()的库,其错误不高于1-2毫秒?

Does anyone know a Library which provides a Thread.sleep() for Java which has an error not higher than 1-2 Millisecond?

我尝试了睡眠,错误测量和BusyWait的混合,但我不能在不同的Windows机器上获得这种可靠性。

I tried a mixture of Sleep, error measurement and BusyWait but I don't get this reliable on different windows machines.

如果该实现也可用于Linux和MacOS,它可以是本机实现。

It can be a native implementation if the implementation is available for Linux and MacOS too.

编辑
Nick提供的链接( http://blogs.oracle.com / dholmes / entry / inside_the_hotspot_vm_clocks )是一个非常好的资源,可以理解java所有类型的定时器/睡眠/时钟的问题。

EDIT The link Nick provided ( http://blogs.oracle.com/dholmes/entry/inside_the_hotspot_vm_clocks ) is a really good resource to understand the issues all kinds of timers/sleeps/clocks java has.

推荐答案

为了提高睡眠粒度,您可以尝试以下 Thread.sleep 页。

To improve granularity of sleep you can try the following from this Thread.sleep page.


Windows下的Thread.sleep()错误

如果时间对你的
应用程序至关重要,那么一个不优雅但
实用的方法来解决这些错误
就是让一个守护程序线程运行

申请期间的整个过程中这只是睡觉
大的素数毫秒
(Long.MAX_VALUE会这样做)。这样,
中断周期将设置为每次调用你的应用程序

最小化对系统
时钟的影响,并将sleep
粒度设置为即使
默认中断周期不是15ms,也是1ms。

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可能会导致用户的时钟快速运行。

The page also mentions that it causes a system-wide change to Windows which may cause the user's clock to run fast due to this bug.

编辑

有关此内容的更多信息,请参阅
此处以及相关的错误报告

More information about this is available here and an associated bug report from Sun.

这篇关于Windows上的Java准确睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆