Question

I want to add a delay of 0.488 ms to my java code. but thread.sleep() and Timer functions only allow a granularity of millisecond. How do I specify a delay amount below that level ?

Was it helpful?

Solution

Since 1.5 you can use this nice method java.util.concurrent.TimeUnit.sleep(long timeout):

TimeUnit.SECONDS.sleep(1);
TimeUnit.MILLISECONDS.sleep(1000);
TimeUnit.MICROSECONDS.sleep(1000000);
TimeUnit.NANOSECONDS.sleep(1000000000); 

OTHER TIPS

You can use Thread.sleep(long millis, int nanos)

Note that you cannot guarantee how precise the sleep will be. Depending on your system, the timer might only be precise to 10ms or so.

TimeUnit.anything.sleep() call Thread.sleep() and Thread.sleep() rounded to milliseconds, all sleep() unusable for less than millisecond accuracy

Thread.sleep(long millis, int nanos) implementation:

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;
}

same situation is with method wait(long, int);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top