Small Example of Java-CountDownLatch
Content: CountDownLatch allows one or more threads to wait for other threads to complete the operation. The CountDownLatch constructor receives an int type parameter as a counter. If you want to wait for N threads or N execution steps, you can pass N as a parameter. When we call the CountDownLatch countDown method once, N will be reduced by 1, and the await of CountDownLatch will block the current thread until N is 0. When multiple threads are used, you only need to pass the reference of CountDownLatch 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); doneSignal. 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.exe cute (new Worker (countDownLatch, I); countDownLatch. await (); System. out. println ("over ");}}