Timer: less than a millisecond period

As a header, is there a way to get the timer to work under the millisecond threshold?

My question is similar to the following, but it is for Java: Thread.Sleep less than 1 millisecond

+7
source share
4 answers

If you want to sleep, Thread.sleep has 2 methods, one of which takes nanoseconds . If you want to schedule a task, you can use ScheduledExecutorService , in which schedule methods can also use nanoseconds.

As @MarkoTopolnik explained, the result will most likely not be accurate for a nanosecond.

+11
source
 Thread.sleep(long millis, int nanos) 

Also check out this answer with details about problems with this on Windows.

+4
source

You can wait for an object that no one will notify ...

 synchronized (someObjectNobodyWillNotify) { try { someObjectNobodyWillNotify.wait(0, nanosToSleep); } catch (InterruptedException e) { Thread.interrupt(); } } 

(In this case, I assume that the false awakenings are in order. If not, you need to write your System.nanoTime() at the beginning and wrap the wait in a loop that checks that enough time has passed.)

+2
source

The java.util.concurrent package uses TimeUnit for synchronization. TimeUnit has a NANOSECONDS field.

+1
source

All Articles