CountDownLatch是Java中的一个同步辅助工具类,它可以让一个或多个线程等待其他线程完成操作后再继续执行。CountDownLatch通过一个计数器来实现,计数器的初始值可以指定,当计数器的值变为0时,所有等待的线程就会被唤醒继续执行。
通常用于以下两种场景:一个线程等待多个其他线程执行完毕后再继续执行; 多个线程等待某个共同事件的发生后再继续执行。
CountDownLatch
案例一
/**
* CountDownLatch使用案例,配合await()方法使用,线程执行完毕会阻塞在await()这,直至所有线程执行完毕
*/
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int numThreads = 3;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
Thread thread = new Thread(new Worker(latch));
thread.start();
}
latch.await(); // 主线程等待所有子线程完成任务
System.out.println("All threads have completed their tasks. Main thread can continue.");
}
static class Worker implements Runnable {
private CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
// 模拟子线程执行任务
Thread.sleep((long) (Math.random() * 1000));
System.out.println("Task completed by thread: " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // 子线程完成任务后调用countDown减少计数器
}
}
}
}
输出结果:
Task completed by thread: Thread-2
Task completed by thread: Thread-0
Task completed by thread: Thread-1
All threads have completed their tasks. Main thread can continue.
案例二
/**
* 使用CountDownLatch完成多个游戏玩家进度条的加载
* 直到所有玩家进度条加载完毕,游戏就可以启动了
*/
public class ProgressBarWithCountDownLatch {
public static void main(String[] args) throws InterruptedException {
int numThreads = 3;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
Thread thread = new Thread(new Task(latch, "Thread-" + i));
thread.start();
}
latch.await(); // 等待所有线程加载完毕
System.out.println("All progress bars have completed. Main t