How accurate is Thread.sleep?

試著忘記壹切 提交于 2019-11-26 11:24:12

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.

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.

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.

From the Java language specification.

Thread.sleep causes the currently executing thread to sleep (temporarily cease execution) for the specified duration, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors, and resumption of execution will depend on scheduling and the availability of processors on which to execute the thread.

mario

I did not find Thread.sleep to be accurate. In fact, I found that it seems to sleep less than what it promises.

Results when configured to sleep 1 millisecond:

********* Average elapsed time = 957 micro seconds

Below is my test:

public static void main(String[] args) throws InterruptedException {
    List<Long> list = new ArrayList<Long>();

    int i= 0;
    while(i <=100){

        long authStartTime = System.nanoTime();
        Thread.sleep(1);
        long elapsedTime = System.nanoTime() - authStartTime;
        System.out.println("*****"+elapsedTime/1000+ " mics");
        list.add(elapsedTime);
        i++;
    }

    long sum=0;
    for(long l : list){
        sum = sum + l;
    }
    System.out.println("********* Average elapsed time = "+sum/list.size()/1000+" micro seconds");
    System.exit(0);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!