MST

星途 面试题库

面试题:Java中Latch的基本作用及简单应用场景

请简要阐述Java中Latch(如CountDownLatch)的作用,并举例说明一个在多线程环境下的简单使用场景,同时编写一段代码展示其基本用法。
37.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

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();
            }
        }
    }
}

在这段代码中:

  1. CountDownLatch的构造函数接受一个初始计数值numThreads
  2. 每个Worker线程在完成任务后调用latch.countDown()方法,将计数器的值减1。
  3. 主线程调用latch.await()方法,等待计数器的值变为0,即所有Worker线程完成任务后再继续执行。