Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
CountDownLatch literally means countdown latches. The two typical uses of CountDownLatch are either one-to-one or one-to-one. The two uses are demonstrated here, and it is important to note that CountDownLatch cannot be reused
Usage 1 (first class more)
A thread waits for multiple threads to complete before resuming its work
package org.example.concurrent; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * this class is used to demonstrate a use of CountDownLatch ** a thread waits for all other threads to complete ** this class assumes that the main thread waits for all five child threads to complete before moving on to the next stage ** @author Catch */ public class CountDownLatchUsage1 { public static void main(String[] args) throws InterruptedException { CountDownLatch latch=new CountDownLatch(5); ExecutorService executorService = Executors.newFixedThreadPool(5); for (int i = 0; i < 5; i++) { int no=i+1; Runnable r=()->{ try { Thread.sleep((long) (Math.random()*10000)); System.out.println("No."+ No +" finished checking "); } catch (InterruptedException e) { e.printStackTrace(); }finally{ latch.countDown(); }}; executorService.submit(r); } system.out. println(" Wait for 5 child threads to complete the check...") ); latch.await(); System.out.println(" All child threads have finished checking and are starting the next phase."); }}Copy the code
Usage 2 (more than one)
Below is a scenario where multiple threads wait for one thread to finish work, and then multiple threads start work at the same time
package org.example.concurrent; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * This class is used to demonstrate the use of CountDownLatch. * Multiple threads wait for one thread to complete work, and then multiple threads start working at the same time. * * @author Catch */ public class CountDownLatchUsage2 {public static void CountDownLatchUsage2 {public static void CountDownLatchUsage2 main(String[] args) throws InterruptedException { CountDownLatch begin=new CountDownLatch(1); CountDownLatch end = new CountDownLatch(1000); ExecutorService executorService = Executors.newFixedThreadPool(1000); for (int i = 0; i < 1000; I++) {Runnable r=()->{try {// some preparation or initialization can be done before begin.await(); begin.await(); Thread.sleep((long) (math.random () * 5000)); System.out.println(thread.currentThread ().getName())+ ); } catch (InterruptedException e) { e.printStackTrace(); }finally{ end.countDown(); }}; executorService.submit(r); } Thread.sleep(3000); System.out.println(" All threads ready, pressure test started!") ); begin.countDown(); end.await(); System.out.println(" All threads completed, pressure finished!") ); }}Copy the code