java如何阻塞程序
阻塞程序的方法
在Java中,可以通过多种方式实现程序的阻塞。以下是几种常见的方法:
使用Thread.sleep()
Thread.sleep()方法可以让当前线程暂停执行指定的时间。这是一个简单的阻塞方法,适用于需要延迟执行的场景。
try {
Thread.sleep(1000); // 阻塞1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
使用Object.wait()
Object.wait()方法可以让当前线程进入等待状态,直到其他线程调用notify()或notifyAll()唤醒它。通常与synchronized块一起使用。
synchronized (lockObject) {
try {
lockObject.wait(); // 阻塞直到被唤醒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
使用CountDownLatch
CountDownLatch是一个同步辅助类,可以让一个或多个线程等待其他线程完成操作。
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
try {
Thread.sleep(1000);
latch.countDown(); // 释放阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
try {
latch.await(); // 阻塞直到countDown被调用
} catch (InterruptedException e) {
e.printStackTrace();
}
使用CyclicBarrier
CyclicBarrier是另一种同步辅助类,可以让一组线程互相等待,直到所有线程都到达某个屏障点。
CyclicBarrier barrier = new CyclicBarrier(2);
new Thread(() -> {
try {
barrier.await(); // 阻塞直到其他线程到达
} catch (Exception e) {
e.printStackTrace();
}
}).start();
try {
barrier.await(); // 阻塞直到其他线程到达
} catch (Exception e) {
e.printStackTrace();
}
使用BlockingQueue
BlockingQueue是一个支持阻塞操作的队列,当队列为空或满时,操作会被阻塞。
BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
try {
String item = queue.take(); // 阻塞直到队列不为空
} catch (InterruptedException e) {
e.printStackTrace();
}
使用Semaphore
Semaphore是一个计数信号量,可以控制同时访问某个资源的线程数量。

Semaphore semaphore = new Semaphore(0);
new Thread(() -> {
try {
Thread.sleep(1000);
semaphore.release(); // 释放许可
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
try {
semaphore.acquire(); // 阻塞直到获取许可
} catch (InterruptedException e) {
e.printStackTrace();
}
注意事项
- 阻塞操作可能会影响程序性能,尤其是在高并发场景中。
- 使用
wait()和notify()时,必须确保在synchronized块中调用,以避免IllegalMonitorStateException。 - 阻塞操作通常需要处理
InterruptedException,以确保线程能够正确响应中断。






