/*** @ Description: Countdown timer. * Like a countdown counter, call the Countdownlatch object's countdown method to reduce the counter by 1, when the calculator is 0 * then all the waiting or a single waiting person starts to execute * @ Author: wnj. * @ creation Time: May 15, 2017. * @ Version: 1.0. */ Public classCountdownlatchtest { Public Static voidMain (string[] args) {Executorservice service=Executors.newcachedthreadpool (); //Whistling FinalCountdownlatch Cdorder =NewCountdownlatch (1); //Waiting for results FinalCountdownlatch Cdanswer =NewCountdownlatch (3); for(inti = 0; I < 3; i++) {Runnable Runnable=NewRunnable () { Public voidrun () {Try{System.out.println ("Thread" + thread.currentthread (). GetName () + "Preparing to accept command"); //cdorder=1 All threads into wait, the above out will printcdorder.await (); System.out.println ("Threads" + thread.currentthread (). GetName () + "accepted command"); Thread.Sleep ((Long) (Math.random () * 10000)); System.out.println ("Threads" + thread.currentthread (). GetName () + "response Command processing results"); //cdanswer=3Cdanswer.countdown (); } Catch(Exception e) {e.printstacktrace (); } } }; Service.execute (runnable); } //Main Thread Try{Thread.Sleep (Long) (Math.random () * 10000)); System.out.println ("Threads" + thread.currentthread (). GetName () + "upcoming Commands"); ////Cdorder=1 will cdorder minus 1 = 0Cdorder.countdown (); System.out.println ("Threads" + thread.currentthread (). GetName () + "sent command, waiting for results"); //cdanswer= 3 Cdanser into the waitingcdanswer.await (); System.out.println ("Threads" + thread.currentthread (). GetName () + "All response results received"); } Catch(Exception e) {e.printstacktrace (); } service.shutdown (); }}
and the contract Java.util.concurrent.CountDownLatch