1 import java.util.concurrent.CountDownLatch; 2 3 /** 4 * @author sulishi 5 * @version 1.0 6 * @date 2021/1/31 7 */ 8 public class CountDownLatchTest { 9 public static void main(String[] args) throws InterruptedException { 10 CountDownLatchTest countDownLatchTest = new CountDownLatchTest(); 11 System.out.println(countDownLatchTest.timeTasks(5, new Runnable() { 12 @Override 13 public void run() { 14 System.out.println("doing something"); 15 } 16 })); 17 } 18 19 20 public long timeTasks(int nThreads, final Runnable task) 21 throws InterruptedException { 22 final CountDownLatch startGate = new CountDownLatch(1); 23 final CountDownLatch endGate = new CountDownLatch(nThreads); 24 25 for (int i = 0; i < nThreads; i++) { 26 Thread t = new Thread() { 27 @Override 28 public void run() { 29 try { 30 //new Thread的时候计数器为1,所有线程都不会执行下面的任务 31 startGate.await(); 32 try { 33 task.run(); 34 } finally { 35 //每个线程执行完成调用-1 36 endGate.countDown(); 37 } 38 } catch (InterruptedException ignored) { 39 } 40 } 41 }; 42 t.start(); 43 } 44 45 long start = System.nanoTime(); 46 //for循环创建所有线程后,再执行startGate.countDown(),计数器减为0,所有线程同时开始抢占资源,执行任务 47 startGate.countDown(); 48 //所有线程未全部执行完,计数器就未减到0,等待 49 endGate.await(); 50 long end = System.nanoTime(); 51 return end - start; 52 } 53 }
CountDownLatch是闭锁的一种灵活实现,闭锁常用于以下场景:
1.确保某个任务在其所需要的全部资源都初始化后才继续执行
2.确保某个服务在其依赖的所有服务都已经启动之后才启动
3.等待某个操作的所有参与者都就绪再继续执行