当我们需要协调多个线程的执行时,可以使用CountDownLatch
来实现。CountDownLatch
是JUC包中提供的一个同步工具类,它可以让一个或多个线程等待其他线程的完成。
下面是一个示例代码,展示了CountDownLatch
的用法:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int threadCount = 3;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
Thread thread = new Thread(new Worker(latch));
thread.start();
}
System.out.println("Main thread is waiting...");
latch.await(); // 主线程等待计数器归零
System.out.println("All workers have completed their tasks. Main thread resumes.");
}
static class Worker implements Runnable {
private final CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println("Worker is performing a task.");
Thread.sleep(2000); // 模拟工作耗时
System.out.println("Worker has completed the task.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // 每个线程完成任务后计数器减一
}
}
}
}
在上述示例中,我们创建了一个CountDownLatch
实例,并将计数器初始值设置为3。然后,我们创建了3个Worker
线程,每个线程都将计数器对象传递给构造函数。
每个Worker
线程在执行任务之前先输出一条消息,然后模拟一个耗时的任务(这里使用Thread.sleep
来模拟)。任务完成后,线程会调用countDown
方法将计数器减一。
主线程通过调用await
方法来等待计数器归零。一旦所有Worker
线程都完成了任务,计数器归零,主线程就会恢复执行,并输出相应的消息。
通过CountDownLatch
,我们可以让主线程等待多个工作线程完成后再继续执行,从而实现了线程间的协调和同步。