java程序如何暂停
暂停 Java 程序的常见方法
Thread.sleep()
通过调用 Thread.sleep(long milliseconds) 方法可以让当前线程暂停指定时间(毫秒)。需处理 InterruptedException。
示例代码:
try {
Thread.sleep(1000); // 暂停1秒
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 恢复中断状态
}
Object.wait()
结合同步块使用 Object.wait(),释放对象锁并暂停线程,直到其他线程调用 notify() 或 notifyAll()。
示例代码:
synchronized (lockObject) {
try {
lockObject.wait(); // 暂停并释放锁
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
LockSupport.park()
使用 LockSupport.park() 暂停当前线程,需通过 LockSupport.unpark(Thread) 恢复。适用于高并发场景。
示例代码:
Thread thread = new Thread(() -> {
LockSupport.park(); // 暂停线程
System.out.println("Resumed");
});
thread.start();
LockSupport.unpark(thread); // 恢复线程
ScheduledExecutorService
通过调度任务实现延迟效果,适合需要定时控制的场景。
示例代码:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(() -> {
System.out.println("Task executed after delay");
}, 2, TimeUnit.SECONDS); // 延迟2秒执行
注意事项

- 避免在主线程中使用
Thread.sleep(),可能导致界面卡顿(如Swing/JavaFX)。 wait()必须配合synchronized使用,否则会抛出IllegalMonitorStateException。- 线程暂停期间可能被中断,需妥善处理中断异常。






