Thread.sleep() 在 Java 中如何暂停线程执行
thread.sleep() 用于让当前正在执行的线程暂停指定时间,期间不释放锁。调用该方法会抛出 interruptedexception,必须处理或声明抛出。它不会停止线程,只是暂时挂起 cpu 占用。

主程序实现与运行方式
以下代码演示了使用 Thread.sleep() 暂停线程的完整流程。程序创建一个新线程,在主线程中启动后,子线程进入睡眠状态,主线程等待其结束后打印结果。
public class SleepDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
System.out.println("Thread started");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("Thread finished");
});
thread.start();
thread.join();
System.out.println("Main thread continues");
}
}预期输出顺序为:
1. Thread started
2. (等待约2秒)
3. Thread finished
4. Main thread continues
该程序验证了 Thread.sleep() 确实暂停了子线程的执行,且不影响主线程的后续操作(通过 join() 确保顺序)。若子线程被中断,会捕获异常并打印中断信息。
立即学习“Java免费学习笔记(深入)”;
基于程序中某个输入、条件或结果的具体问题
当 Thread.sleep() 被中断时,线程会立即退出睡眠状态并抛出 InterruptedException。这可用于优雅地终止长时间运行的任务。例如,在上述代码中,若在睡眠期间调用 thread.interrupt(),子线程将跳过剩余睡眠时间,直接执行异常处理逻辑。


















