我如何保证 Thread.sleep 至少休眠那么长的时间?

How can I guarantee that Thread.sleep sleeps for at least that amount of time?

根据 Thread.sleep 不一定保证在您指定的时间内休眠:它可能更短 更长。

如果您阅读 Thread.sleep 的文档,您会发现对于将要休眠的确切持续时间没有强有力的保证。它特别指出持续时间是

subject to the precision and accuracy of system timers and schedulers

这(有意)含糊但暗示不应过分依赖持续时间。

特定操作系统上可能的休眠持续时间的粒度由线程调度程序的中断周期决定。

In Windows, the scheduler's interrupt period is normally around 10 or 15 milliseconds (which I believe is dictated by the processor), but a higher period can be requested in software and the Hotspot JVM does so when it deems necessary

Source,强调我的

我怎样才能实际保证睡眠持续时间至少是我指定的值?

最实用的解决办法是定时睡觉,在还有时间的时候继续睡觉:

public void sleepAtLeast(long millis) throws InterruptedException
{
    long t0 = System.currentTimeMillis();
    long millisLeft = millis;
    while (millisLeft > 0) {
       Thread.sleep(millisLeft);
       long t1 = System.currentTimeMillis();
       millisLeft = millis - (t1 - t0);
    }
}

代码和信息来自here