简体   繁体   中英

Does Thread.sleep() make the execution to cease for accurate an interval

Here is my code

try{

  System.out.println("Before");
  thread.sleep(10000);//sleep for 10000 ms
  System.out.println("After");

}
catch(ItrerruptedException ie){
//If this thread was intrrupted by nother thread 
}

I just want to know whether the thread will sleep for exaclty 10 seconds and then print After or there is some delay?

From the javadocs: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. Which means it will sleep for at least 10 seconds. It may sleep longer if the scheduler decides to not let it run after the 10 seconds is over.
Which may happen if more concurrent threads are in the runnable pool at the same time.

A non realtime scheduler won't guarantee timing.

If you are doing some kind of hardware communication that really relies on timing, you should probably use RTSJ .

If you are doing something each x milliseconds, you could use a TimeTask that will perform slightly better.

It will sleep for at least 10 seconds, and wake shortly after (unless interrupted). How soon after depends on the OS and the load on the machine.

It's more or less random because your OS task scheduler is usually not required to give your process all the attention it wants. Usually, you will not be able to sleep for very small amounts of time (for example, Thread.sleep(5) might resume your process later than 5 ms after the call), but as you increase the sleep time, the relative precision increases.

If you can tolerate some leeway, Thread.sleep(10000) will usually sleep for an amount of time that's close enough to 10 seconds.

I would say unless you have lots of threads running it's pretty close to exact. If you have several threads then it's a competition.

从睡眠到运行的线程开销非常低。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM