A synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed.
Two inverted-count latches are used below: one to wait 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 accept Command"); cdorder.await (); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "accepted command"); Thread.Sleep ((Long) math.random () *10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "response command, process result"); Cdanswer.countdown (); catch (Interruptedexception e) {e.printstacktrace ();} } }; Threadpool.execute (runnable); try {thread.sleep (long) Math.raNdom () *10000); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "Waiting to publish Command"); Cdorder.countdown (); cdanswer.await (); SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "command issued, waiting for results"); System.out.println ("All commands are processed");} catch (Interruptedexception e) {e.printstacktrace ();} Threadpool.shutdown ();}}
Getting Started with Countdownlatch thread synchronization in Java