sleep
在指定毫秒数内,让正在执行的当前线程进入休眠期。
示例
public class SleepDemo extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
}
public static void main(String[] args) {
SleepDemo demo = new SleepDemo();
demo.setName("demo");
demo.start();
try {
System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "-" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果如下:

结果可以看出,main线程的两次时间相差1000毫秒,demo的两次时间相差2000毫秒,sleep只影响自己的线程运行,不影响其他线程。
本文详细介绍了Java中Thread.sleep(long millis)方法的使用方法及其对线程的影响。通过一个具体的SleepDemo示例展示了如何使当前线程暂停执行指定的毫秒数。
793

被折叠的 条评论
为什么被折叠?



