Content: Countdownlatch allows one or more threads to wait for another thread to complete the operation. The Countdownlatch constructor takes a parameter of type int as a counter, and if you want to wait for n threads or wait for N to execute the steps, you can pass n as a parameter. When we call the countdown method of the Countdownlatch, N will reduce the 1,countdownlatch of the await to block the current thread until n is 0. When used with multiple threads, you only need to pass this countdownlatch reference to the thread.
public class Countdownlatchtest {static Class Worker implements Runnable {private final Countdownlatch donesignal;private Final int i;public Worker (countdownlatch donesignal, int i) {this.donesignal = Donesignal;this.i = i;} @Overridepublic void Run () {System.out.println ("now is" + i);d onesignal.countdown ();}} public static void Main (string[] args) throws interruptedexception {int N = 10; Countdownlatch Countdownlatch = new Countdownlatch (N); Executorservice executor = Executors.newfixedthreadpool (n), for (int i = 0; i < N; i++) Executor.execute (New Worker (Coun Tdownlatch, i)); countdownlatch.await (); System.out.println ("Over");}}
A small example of Java-countdownlatch