Java 5 multithreading (6)-countdownlatch synchronization Tool

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.