
sleep()方法是Thread类的静态方法,它使线程 >睡眠/停止工作一段特定的时间。如果一个线程被其他线程中断,sleep() 方法会抛出 InterruptedException,这意味着 Thread.sleep() 方法必须包含在 try 中,并且catch 块或者必须用抛出子句指定。每当我们调用Thread.sleep()方法时,它都会与线程调度程序交互,将当前线程置于等待状态一段时间。特定的时间段。一旦等待时间结束,线程就会从等待状态更改为可运行状态。
语法
public static void sleep(long milliseconds) public static void sleep(long milliseconds, int nanoseconds)
sleep(long milliseconds) 方法使线程仅休眠某些特定的毫秒。
sleep(long milliseconds) 方法使线程仅休眠某些特定的毫秒。毫秒,整数纳秒)方法使线程休眠一些特定的毫秒加纳秒。
示例
class UserThread extends Thread {
public void run() {
for(int i=1; i <= 5; i++) {
System.out.println("User Thread");
try {
<strong> </strong> Thread.sleep(1000); // sleep/stop a thread for 1 second<strong>
</strong> } catch(InterruptedException<strong> </strong>e) {
System.out.println("An Excetion occured: " + e);
}
}
}
}
public class SleepMethodTest {
public static void main(String args[]) {
UserThread ut = new UserThread();
<strong> </strong> ut.start(); // to start a thread
}
}输出
User Thread User Thread User Thread User Thread User Thread











