Getting started with CountDownLatch thread synchronization in java
A synchronization helper class that allows one or more threads to wait until a group of operations are performed in another thread.
Two inverted-count latches are used below: one is waiting for the other to complete.
Import java. util. concurrent. countDownLatch; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class CountDownLatchTest {/*** @ param args */public static void main (String [] args) {ExecutorService ThreadPool = Executors. newCachedThreadPool (); final CountDownLatch cdOrder = new CountDownLatch (1); final CountDownLatch cdAnswer = new CountDownLatch (3); for (int I = 0; I <3; I ++) {Runnable runnable = new Runnable () {@ Override public void run () {try {System. out. println ("Thread" + Thread. currentThread (). getName () + "waiting to receive command"); cdOrder. await (); System. out. println ("Thread" + Thread. currentThread (). getName () + "commands accepted"); Thread. sleep (long) Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "response command, processing result"); cdAnswer. countDown ();} catch (InterruptedException e) {e. printStackTrace () ;}}; ThreadPool.exe cute (runnable);} try {Thread. sleep (long) Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "waiting for command release"); cdOrder. countDown (); cdAnswer. await (); System. out. println ("Thread" + Thread. currentThread (). getName () + "command released, waiting for result"); System. out. println ("All commands have been processed");} catch (InterruptedException e) {e. printStackTrace ();} ThreadPool. shutdown ();}}