向 Java 代码添加十进制毫秒延迟



我想在我的java代码中添加0.488毫秒的延迟。 但是thread.sleep()和Timer 函数只允许毫秒的粒度。如何指定低于该级别的延迟量?

从 1.5 开始,您可以使用这个不错的方法java.util.concurrent.TimeUnit.sleep(long timeout)

TimeUnit.SECONDS.sleep(1);
TimeUnit.MILLISECONDS.sleep(1000);
TimeUnit.MICROSECONDS.sleep(1000000);
TimeUnit.NANOSECONDS.sleep(1000000000); 
您可以使用

Thread.sleep(long millis, int nanos)

请注意,您无法保证睡眠的精确度。根据您的系统,计时器可能只精确到 10 毫秒左右。

TimeUnit.anything.sleep() 调用 Thread.sleep() 和 Thread.sleep() 四舍五入到毫秒,所有 sleep() 在小于毫秒的精度下不可用

Thread.sleep(long millis, int nanos) 实现:

public static void sleep(long millis, int nanos) throws java.lang.InterruptedException
{
  ms = millis;
  if(ms<0) {
    // exception "timeout value is negative"
    return;
  }
  ns = nanos;
  if(ns>0) {
    if(ns>(int) 999999) {
      // exception "nanosecond timeout value out of range"
      return;
    }
  }
  else {
    // exception "nanosecond timeout value out of range"
    return;
  }
  if(ns<500000) {
    if(ns!=0) {
      if(ms==0) { // if zero ms and non-zero ns thread sleep 1ms
        ms++;
      }
    }
  }
  else {
    ms++;
  }
  sleep(ms);
  return;
}

方法wait(long,int)也是如此;

最新更新