在Java中,CountDownLatch是一个同步辅助类,它可以让一个或多个线程等待其他线程完成操作后再继续执行。CountDownLatch可以用于以下场景:
-
主线程等待多个子线程完成后再执行。
-
多个子线程等待主线程完成某个任务后再开始执行。
CountDownLatch的使用步骤如下:
-
创建一个CountDownLatch对象,指定需要等待的线程数量。
-
在需要等待的线程中,调用CountDownLatch的await()方法,使线程进入等待状态,直到计数器减为0。
-
在其他线程执行完需要等待的任务后,调用CountDownLatch的countDown()方法,将计数器减1。
-
如果主线程需要等待其他线程完成后再执行,可以在主线程中调用CountDownLatch的await()方法,使主线程进入等待状态。
-
当计数器减到0时,所有等待的线程将被唤醒,继续执行。
下面是一个简单的示例代码:
import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { public static void main(String[] args) { int threadCount = 5; CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(new WorkerThread(latch)); thread.start(); } try { latch.await(); // 主线程等待所有子线程执行完毕 System.out.println("All threads have finished."); } catch (InterruptedException e) { e.printStackTrace(); } } } class WorkerThread implements Runnable { private CountDownLatch latch; public WorkerThread(CountDownLatch latch) { this.latch = latch; } @Override public void run() { // 执行需要等待的任务 System.out.println("Thread " + Thread.currentThread().getName() + " is running."); // 任务执行完毕后,调用countDown()方法将计数器减1 latch.countDown(); } }
在上面的示例代码中,主线程创建了5个WorkerThread线程,并将CountDownLatch对象作为参数传递给它们。每个WorkerThread线程执行完任务后,调用latch.countDown()方法将计数器减1。主线程调用latch.await()方法进入等待状态,直到计数器减为0,所有子线程执行完成。最后,主线程输出"All threads have finished."。