JAVA如何设置暂停
设置线程暂停
在Java中,可以使用Thread.sleep()方法让当前线程暂停执行一段时间。该方法接受一个以毫秒为单位的时间参数。
try {
Thread.sleep(1000); // 暂停1秒
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重新设置中断状态
System.err.println("Thread interrupted");
}
使用TimeUnit进行更可读的暂停
TimeUnit类提供了更可读的方式来指定时间单位,如秒、分钟等。
try {
TimeUnit.SECONDS.sleep(1); // 暂停1秒
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread interrupted");
}
使用Object.wait()实现条件暂停
Object.wait()方法可以让线程暂停,直到另一个线程调用notify()或notifyAll()。

synchronized (lockObject) {
try {
lockObject.wait(); // 暂停线程,等待通知
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread interrupted");
}
}
使用ScheduledExecutorService定时暂停
ScheduledExecutorService可以安排任务在指定的延迟后运行。
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(() -> {
System.out.println("Task executed after delay");
}, 1, TimeUnit.SECONDS); // 1秒后执行
executor.shutdown();
使用LockSupport暂停线程
LockSupport类提供了park()和unpark()方法,可以更灵活地控制线程的暂停和恢复。

Thread thread = new Thread(() -> {
System.out.println("Thread is parking");
LockSupport.park(); // 暂停线程
System.out.println("Thread is unparked");
});
thread.start();
// 恢复线程
LockSupport.unpark(thread);
使用CountDownLatch同步暂停
CountDownLatch可以让线程等待,直到计数器减到零。
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
try {
latch.await(); // 暂停线程,直到计数器为零
System.out.println("Thread resumed");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}).start();
// 恢复线程
latch.countDown();
使用CyclicBarrier同步暂停
CyclicBarrier可以让一组线程互相等待,直到所有线程都到达屏障点。
CyclicBarrier barrier = new CyclicBarrier(2);
new Thread(() -> {
try {
System.out.println("Thread 1 waiting");
barrier.await(); // 暂停线程,直到所有线程到达
System.out.println("Thread 1 resumed");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
System.out.println("Thread 2 waiting");
barrier.await(); // 暂停线程,直到所有线程到达
System.out.println("Thread 2 resumed");
} catch (Exception e) {
e.printStackTrace();
}
}).start();






