CountDownLatch
不是一种锁,而是一种同步工具类,用于协调多个线程之间的操作。它并不是像 ReentrantLock
或 synchronized
关键字那样实现了锁定机制,而是通过一个计数器来实现线程的等待和通知。
具体来说,CountDownLatch
维护了一个计数器,这个计数器的初始值由调用者在创建 CountDownLatch
对象时指定。每次调用 countDown()
方法,计数器的值减一;而调用 await()
方法会阻塞当前线程,直到计数器的值减到零。这个类主要用于一个或多个线程等待其他线程完成某些操作后再继续执行。
实际上,CountDownLatch
并没有像锁一样控制对临界区的访问,而是提供了一种不同的线程协作机制。它通常用于一组线程需要等待另一组线程完成操作的场景。
import java.util.concurrent.CountDownLatch;public class CountDownLatchExample {public static void main(String[] args) throws InterruptedException {int numberOfTasks = 3;CountDownLatch latch = new CountDownLatch(numberOfTasks);// 创建并启动三个线程执行任务for (int i = 0; i < numberOfTasks; i++) {new TaskThread(latch).start();}// 主线程等待计数器归零latch.await();System.out.println("All tasks are completed.");}static class TaskThread extends Thread {private final CountDownLatch latch;public TaskThread(CountDownLatch latch) {this.latch = latch;}@Overridepublic void run() {try {// 模拟执行任务的耗时操作Thread.sleep(2000);System.out.println("Task completed by thread: " + Thread.currentThread().getName());} catch (InterruptedException e) {e.printStackTrace();} finally {// 任务完成后计数器减一latch.countDown();}}}
}