static void sleep(long millis)
描述 (Description)
java.lang.Thread.sleep(long millis)方法使当前正在执行的线程休眠指定的毫秒数,具体取决于系统定时器和调度程序的精度和准确性。
声明 (Declaration)
以下是java.lang.Thread.sleep()方法的声明
public static void sleep(long millis) throws InterruptedException
参数 (Parameters)
millis - 这是以毫秒为单位的睡眠时间。
返回值 (Return Value)
此方法不返回任何值。
异常 (Exception)
InterruptedException - 如果有任何线程中断了当前线程。 抛出此异常时,将清除当前线程的中断状态。
例子 (Example)
以下示例显示了java.lang.Thread.sleep()方法的用法。
package com.iowiki;
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