Java.lang.Thread.sleep() 方法
描述
java.lang.Thread.sleep(long millis) 方法使当前执行的线程休眠指定的毫秒数,这取决于系统计时器和调度程序的精度和准确性。
声明
以下是 java.lang.Thread.sleep() 方法的声明。
public static void sleep(long millis) throws InterruptedException
参数
millis − 这是休眠的时间长度,以毫秒为单位。
返回值
此方法不返回任何值。
异常
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
Thread.sleep(1000);
} 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

