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 ?
Asked
Active
Viewed 2.4k times
3 Answers
15
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);
-
1You can't rely on this if you want to wait small number of microseconds. The only way to do this is to busy wait on a thread. – Dan Oct 26 '15 at 18:19
4
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.
Cameron Skinner
- 48,389
- 2
- 64
- 82
-
In WIndows JDK1.6.0_37, this method just add one millisecond, and call Thread.sleep(). It is fully ignoring nanos time. – kornero Nov 27 '12 at 06:25
-
1@kornero: That's exactly why you cannot guarantee the precision of this method :) Nevertheless, on some systems you can get sub-millisecond precision. – Cameron Skinner Nov 27 '12 at 07:01
2
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);
user3133528
- 21
- 1