Java.lang.Thread.sleep() 方法
描述
java.lang.Thread.sleep(long millis, int nanos) 方法使当前正在执行的线程休眠指定的毫秒数加上指定的纳秒数,具体取决于 系统计时器和调度程序。
声明
以下是 java.lang.Thread.sleep() 方法的声明。
public static void sleep(long millis, int nanos) throws InterruptedException
参数
millis − This is the length of time to sleep in milliseconds.
nanos − This is 0-999999 additional nanoseconds to sleep.
返回值
此方法不返回任何值。
异常
IllegalArgumentException − 如果millis的值为负数或nanos的值不在0-999999范围内。
InterruptedException − 如果任何线程中断了当前线程。 抛出此异常时清除当前线程的中断状态。
示例
下面的例子展示了 java.lang.Thread.sleep() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class ThreadDemo implements Runnable {
Thread t;
public void run() {
for (int i = 10; i < 13; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
try {
// thread to sleep for 1000 milliseconds plus 500 nanoseconds
Thread.sleep(1000, 500);
} catch (Exception e) {
System.out.println(e);
}
}
}
public static void main(String[] args) throws Exception {
Thread t = new Thread(new ThreadDemo());
// this will call run() function
t.start();
Thread t2 = new Thread(new ThreadDemo());
// this will call run() function
t2.start();
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Thread-0 10 Thread-1 10 Thread-0 11 Thread-1 11 Thread-0 12 Thread-1 12

