Java Thread.sleep for minimum time [duplicate]

僤鯓⒐⒋嵵緔 提交于 2019-12-23 09:34:27

问题


The TimeUnit.sleep(long timeout) documentation describes its argument thus:

timeout - the minimum time to sleep.

However, I'm finding that — at least on Windows 7 64-bit with Java 8 update 141 — the thread often sleeps for less than the minimum:

public static void main(String[] args) throws InterruptedException {
    final long from = TimeUnit.MILLISECONDS.toNanos(100);
    final long to   = TimeUnit.MILLISECONDS.toNanos(1000);
    final long step = TimeUnit.MILLISECONDS.toNanos(100);
    for (long requestedSleepDuration = from; requestedSleepDuration < to; requestedSleepDuration += step) {
        long sleepStartTime = System.nanoTime();
        TimeUnit.NANOSECONDS.sleep(requestedSleepDuration);
        long sleepEndTime = System.nanoTime();
        System.out.printf(
                "requested=%9d  actual=%9d  %s%n",
                requestedSleepDuration,
                sleepEndTime - sleepStartTime,
                (sleepEndTime - sleepStartTime >= requestedSleepDuration ? "OK" : " Slept less than minimum!"));
    }
}

Typical output:

requested=100000000  actual= 99534864  Slept less than minimum!
requested=200000000  actual=200063646  OK
requested=300000000  actual=299223086  Slept less than minimum!
requested=400000000  actual=399598620  Slept less than minimum!
requested=500000000  actual=499910360  Slept less than minimum!
requested=600000000  actual=600028523  OK
requested=700000000  actual=699604816  Slept less than minimum!
requested=800000000  actual=799230602  Slept less than minimum!
requested=900000000  actual=899490648  Slept less than minimum!

This seems to contradict the documentation. However, the TimeUnit doc also states that TimeUnit.sleep() is a convenience wrapper for Thread.sleep, and the latter doesn't say if it guarantees to sleep at least the specified amount.

Is this an API implementation error, or is TimeUnit.sleep and/or Thread.sleep designed to only sleep for approximately, rather than at least, the specified duration?


回答1:


TimeUnit.sleep() delegates to Thread.sleep().

Thread.sleep() is subject to the precision and accuracy of system timers and schedulers, thus TimeUnit.sleep() will not be as accurate as you may need.



来源:https://stackoverflow.com/questions/45419940/java-thread-sleep-for-minimum-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!