面试题答案
一键面试Latch的作用
在Java中,Latch
(如CountDownLatch
)是一种同步工具,它允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。CountDownLatch
通过一个计数器来实现这一功能,当计数器的值减为0时,等待的线程就会被释放。
简单使用场景
一个常见的场景是主线程等待多个子线程完成各自的任务后再继续执行。例如,在一个数据分析程序中,可能有多个线程分别负责从不同的数据源读取数据,主线程需要等待所有这些数据读取操作完成后,再进行数据的汇总和分析。
代码示例
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
int numThreads = 3;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
new Thread(new Worker(latch, "Thread-" + i)).start();
}
try {
System.out.println("Main thread waiting for all workers to finish...");
latch.await();
System.out.println("All workers have finished. Main thread can continue.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Worker implements Runnable {
private final CountDownLatch latch;
private final String name;
public Worker(CountDownLatch latch, String name) {
this.latch = latch;
this.name = name;
}
@Override
public void run() {
try {
System.out.println(name + " is working...");
// 模拟实际工作
Thread.sleep((long) (Math.random() * 2000));
System.out.println(name + " has finished.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
}
在这段代码中:
CountDownLatch
的构造函数接受一个初始计数值numThreads
。- 每个
Worker
线程在完成任务后调用latch.countDown()
方法,将计数器的值减1。 - 主线程调用
latch.await()
方法,等待计数器的值变为0,即所有Worker
线程完成任务后再继续执行。