The detailed code is as follows: public class countdownlatchtest {public static void main (string [] ARGs) {executorservice service = executors. newcachedthreadpool (); Final countdownlatch cdorder = new countdownlatch (1); final countdownlatch cdanswer = new countdownlatch (3); For (INT I = 0; I <3; I ++) {runnable = new runnable () {public void run () {try {system. out. println ("Thread" + thread. currentthread (). getname () + "preparing to accept command"); cdorder. await (); // This program can be executed only when the cdorder counter is set to 0. // if this program is equivalent to a game where three athletes are playing, another counter of the referee // cdorder is 0, indicating that the referee's name gun is ready for the athlete to run. 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 (); // when each athlete reaches this counter, one is subtracted,} catch (exception e) {e. printstacktrace () ;}}; service.exe cute (runnable);} Try {thread. sleep (long) (math. random () * 10000); system. out. println ("Thread" + thread. currentthread (). getname () + "coming soon"); cdorder. countdown (); // the counter of cdorder minus 1, system. out. println ("Thread" + thread. currentthread (). getname () + "sent command, waiting for result"); cdanswer. await (); // cdanswer until the counter is 0, that is, the execution of the preceding three threads is complete. // The referee can publish the result system. out. println ("Thread" + thread. currentthread (). getname () + "all response results received");} catch (exception e) {e. printstacktrace ();} service. shutdown ();}
}
The execution result is as follows:
Reprinted please indicate the source: http://blog.csdn.net/johnny901114/article/details/8695726