java如何sleep
在Java中使用sleep方法
Java中实现线程暂停的主要方式是使用Thread.sleep()方法。该方法可以让当前执行的线程暂停指定的毫秒数。

基本语法
try {
Thread.sleep(毫秒数);
} catch (InterruptedException e) {
// 处理中断异常
Thread.currentThread().interrupt();
}
参数说明
- 毫秒数:线程需要暂停的时间长度,以毫秒为单位
- 可选的纳秒参数:
Thread.sleep(long millis, int nanos)
使用示例
public class SleepExample {
public static void main(String[] args) {
System.out.println("开始执行");
try {
// 暂停3秒
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("睡眠被中断");
}
System.out.println("3秒后继续执行");
}
}
注意事项
sleep()方法会抛出InterruptedException,必须处理这个检查型异常- 睡眠时间结束后,线程会进入就绪状态,等待CPU调度
- 实际睡眠时间可能略长于指定时间,取决于系统计时器和调度器
- 在睡眠期间线程不会释放任何锁
替代方案
对于更复杂的时间控制,可以考虑:
TimeUnit.SECONDS.sleep(1); // 使用TimeUnit更可读
中断处理
当线程在sleep时被中断,会立即抛出InterruptedException:
Thread t = new Thread(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("我被唤醒了");
}
});
t.start();
t.interrupt(); // 中断睡眠中的线程







