gpt4 book ai didi

Java Thread.sleep 最短时间

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:24:08 25 4
gpt4 key购买 nike

<分区>

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

timeout - the minimum time to sleep.

但是,我发现 — 至少在带有 Java 8 update 141 的 Windows 7 64 位上 — 线程 hibernate 的时间通常少于:

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 的便利包装器,而后者没有说明它是否保证至少 sleep 指定数量。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com