多线程(七、同步计数器-CountDownLatch)
CountDownLatch是一个线程的同步计数器,主要有2个使用场景。 1、作为一个开关,N个子线程准备就绪,等待主线程的放行,然后子线程一起开始执行。 Task package com.jane; import java.util.concurrent.CountDownLatch; public class Task implements Runnable { private CountDownLatch countDownLatch; private String name; public Task(CountDownLatch countDownLatch, String name) { this.countDownLatch = countDownLatch; this.name = name; } @Override public void run() { try { System.out.println(name + "开始等待开关......"); countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + "执行任务完成"); } } 主线程 public class Main { public static