一 点睛
sleep 是一个静态方法,它有两个重载方法,其中一个需要传入毫秒数,另外一个需要传入毫秒数和纳秒数。
sleep 的方法
public static native void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException
sleep 方法会使当前线程进入指定毫秒数的休眠,暂停执行,虽然给定了一个休眠的时间,但是最终要以系统的定时器和调度器的精度为准。
二 实战
1 代码
package concurrent;
import static java.lang.Thread.sleep;
public class ThreadSleep {
public static void main(String[] args) {
new Thread(() -> {
long startTime = System.currentTimeMillis();
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(String.format("Total spend %d ms", (endTime - startTime)));
}).start();