简体   繁体   English

Thread.sleep()是否使执行停止准确的时间间隔

[英]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? 我只想知道线程是否将休眠10秒,然后打印After还是有一些延迟?

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. 来自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. 这意味着它将休眠至少10秒钟。 It may sleep longer if the scheduler decides to not let it run after the 10 seconds is over. 如果调度程序决定在10秒结束后不让其运行,则它可能会休眠更长的时间。
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 . 如果您要进行某种确实依赖时序的硬件通信,则可能应该使用RTSJ

If you are doing something each x milliseconds, you could use a TimeTask that will perform slightly better. 如果您每x毫秒执行一次操作,则可以使用TimeTask ,它的性能会稍好一些。

It will sleep for at least 10 seconds, and wake shortly after (unless interrupted). 它将休眠至少10秒钟,然后不久唤醒(除非被打断)。 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. 它或多或少是随机的,因为通常不需要您的OS任务计划程序来给您的进程所需的全部注意力。 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. 通常,您将无法长时间睡眠(例如, Thread.sleep(5)可能会在调用后5毫秒后恢复进程),但是随着睡眠时间的增加,相对精度会提高。

If you can tolerate some leeway, Thread.sleep(10000) will usually sleep for an amount of time that's close enough to 10 seconds. 如果您可以忍受一些回旋余地,则Thread.sleep(10000)通常会休眠一段时间,该时间足够接近10秒。

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. 如果您有多个线程,那就是竞争。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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