这是我的代码
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
}
我只想知道线程是否会休眠 10 秒然后打印After
或者有一些延迟?
这是我的代码
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
}
我只想知道线程是否会休眠 10 秒然后打印After
或者有一些延迟?
来自 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.
这意味着它将至少休眠 10 秒。如果调度程序决定在 10 秒结束后不让它运行,它可能会休眠更长时间。
如果更多并发线程同时在可运行池中,则可能会发生这种情况。
它会休眠至少 10 秒,然后很快就会醒来(除非被打断)。多久之后取决于操作系统和机器上的负载。
它或多或少是随机的,因为您的操作系统任务调度程序通常不需要为您的进程提供所需的所有关注。通常,您将无法休眠很短的时间(例如,Thread.sleep(5)
可能会在调用后 5 毫秒后恢复您的进程),但随着您增加休眠时间,相对精度会增加。
如果您可以容忍一些余地,Thread.sleep(10000)
通常会睡足够接近 10 秒的时间。
我会说除非你有很多线程运行它非常接近准确。如果你有几个线程,那么这是一个竞争。
线程从休眠到运行的开销非常低。