java如何暂停
暂停线程的方法
在Java中暂停线程可以通过Thread.sleep()方法实现。该方法使当前线程暂停执行指定的毫秒数。
try {
Thread.sleep(1000); // 暂停1秒
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重新设置中断标志
System.out.println("Thread was interrupted");
}
使用wait()和notify()
通过wait()方法可以让线程进入等待状态,直到其他线程调用notify()或notifyAll()唤醒它。
synchronized (lockObject) {
try {
lockObject.wait(); // 线程暂停,释放锁
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 另一个线程中
synchronized (lockObject) {
lockObject.notify(); // 唤醒等待的线程
}
暂停程序执行
如果需要暂停整个程序的执行,可以通过循环或条件判断实现。
while (pauseFlag) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
使用ScheduledExecutorService
通过ScheduledExecutorService可以安排任务在延迟后执行。

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(() -> {
System.out.println("Task executed after delay");
}, 2, TimeUnit.SECONDS); // 延迟2秒执行
executor.shutdown();
注意事项
Thread.sleep()不会释放锁,而wait()会释放锁。- 处理中断异常时应恢复中断标志,避免吞没中断信号。
- 使用
wait()和notify()时必须在同步块中调用。






