Java中Thread.sleep()方法的用途是什么?
在睡眠() 方法是一个静态 的方法线程 类,它使线程睡眠/停止的时间具体数额的工作。如果某个线程被其他线程中断,则该sleep()方法将引发InterruptedException ,这意味着Thread.sleep()方法必须包含在try和catch块内,或者必须使用throws 子句指定。每当我们调用Thread.sleep()方法时,它都可以与线程调度程序交互以将当前线程置于等待状态在特定时间段内。等待时间结束后,线程将从等待 状态更改为可运行 状态。
语法
public static void sleep(long milliseconds) public static void sleep(long milliseconds, int nanoseconds)
在睡眠(长毫秒)方法使一个线程睡眠只有一些特定毫秒。
在睡眠(长毫秒,INT纳秒)方法使一个线程睡眠的一些具体毫秒加纳秒。
示例
class UserThread extends Thread {
public void run() {
for(int i=1; i <= 5; i++) {
System.out.println("User Thread");
try { Thread.sleep(1000); // sleep/stop a thread for 1 second } catch(InterruptedException e) {
System.out.println("An Excetion occured: " + e);
}
}
}
}
public class SleepMethodTest {
public static void main(String args[]) {
UserThread ut = new UserThread(); ut.start(); // to start a thread
}
}输出结果
User Thread User Thread User Thread User Thread User Thread
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短