Java线程睡眠
时间:2020-02-23 14:35:16 来源:igfitidea点击:
java.lang.Thread的Sleep方法用于在特定时间段内“暂停线程的当前执行”。
关于Sleep方法的一些重要点是:
- 它导致电流执行线程以睡眠特定的时间。
- 它的准确性取决于
system timers and schedulers。 - 它保留了它所获得的监视器,所以如果它被调用
synchronized背景信息,没有其他线程可以输入该块或者方法。 - 如果我们调用
interrupt()方法,它会唤醒睡眠线程。
synchronized(lockedObject) {
Thread.sleep(1000); //It does not release the lock on lockedObject.
//So either after 1000 miliseconds, current thread will wake up, or after we call
//t. interrupt() method.
示例:创建一个类 FirstThread.java如下。
package org.igi.theitroad.thread;
public class FirstThread implements Runnable{
public void run()
{
System.out.println("Thread is running");
}
}
创建名为的主类 ThreadSleepExampleMain.java
package org.igi.theitroad.thread;
public class ThreadSleepExampleMain {
public static void main(String args[])
{
FirstThread ft= new FirstThread();
Thread t=new Thread(ft);
t.start();
long startTime=System.currentTimeMillis();
try {
//putting thread on sleep
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime=System.currentTimeMillis();
long timeDifference=(endTime-startTime);
System.out.println("Time difference between before and after sleep call: "+timeDifference);
}
}
我们可以看到延迟1000毫秒(1秒)。
如前所述,其准确性取决于系统定时器和调度率。
线程睡眠如的工作原理
Thread.sleep()适用于线程调度程序,暂停特定时间段的当前线程执行。
一旦线程等待期结束,线程的状态再次更改为Runnable,它可用于CPU的进一步执行。

