java如何阻塞线程
阻塞线程的方法
在Java中,可以通过多种方式实现线程阻塞。以下是几种常见的方法:
使用 Thread.sleep()
Thread.sleep(long millis) 方法使当前线程暂停执行指定的毫秒数。线程进入 TIMED_WAITING 状态,不会释放锁。
try {
Thread.sleep(1000); // 阻塞1秒
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
使用 Object.wait()
wait() 方法使线程进入等待状态,直到其他线程调用 notify() 或 notifyAll()。调用前必须持有对象的监视器锁(即在 synchronized 块中)。
synchronized (lockObject) {
try {
lockObject.wait(); // 释放锁并阻塞
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
使用 Lock 和 Condition
java.util.concurrent.locks.Lock 接口的 Condition 提供了更灵活的阻塞机制,类似于 wait()/notify(),但支持多个条件队列。
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
lock.lock();
try {
condition.await(); // 释放锁并阻塞
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
使用阻塞队列
BlockingQueue(如 ArrayBlockingQueue)的 take() 或 put() 方法会在队列空或满时自动阻塞线程。
BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
try {
String item = queue.take(); // 队列空时阻塞
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
使用 CountDownLatch
CountDownLatch 允许线程等待直到计数器归零。

CountDownLatch latch = new CountDownLatch(1);
try {
latch.await(); // 阻塞直到countDown()被调用
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
注意事项
- 阻塞方法(如
sleep()、wait()、await())通常会抛出InterruptedException,需妥善处理中断信号。 - 使用
wait()或Condition时,必须确保在阻塞前持有正确的锁。 - 根据场景选择合适工具:简单延迟用
sleep(),线程协作用wait()/Condition,任务协调用CountDownLatch或CyclicBarrier。






