Java Thread.sleep最短时间

时间:2017-07-31 15:33:09

标签: java thread-sleep

TimeUnit.sleep(long timeout)文档描述了它的论点:

  

超时 - 最短睡眠时间。

但是,我发现 - 至少在带有Java 8更新141的Windows 7 64位上 - 线程通常会睡眠而不是最小值:

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!"));
    }
}

典型输出:

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!

这似乎与文档相矛盾。但是,TimeUnit文档还指出TimeUnit.sleep()Thread.sleep的便利包装器,而后者并未说明它是否保证至少睡眠时间为。{/ p>

这是一个API实现错误,还是TimeUnit.sleep和/或Thread.sleep设计为只为大约而不是至少休眠,指定的持续时间?

1 个答案:

答案 0 :(得分:3)

TimeUnit.sleep()代表Thread.sleep()

Thread.sleep()受制于系统计时器和计划程序的精确性和准确性,因此TimeUnit.sleep()不会像您需要的那样准确。