Java multithreading countdownlatch

Source: Internet
Author: User
Import Java. util. concurrent. countdownlatch; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors;/*** countdownlatch is a counter, which has an initial number. * The thread waiting for this counter must wait until the countdown to zero to continue. */Public class countdownlatchtest {/*** initialize component thread */public static class componentthread implements runnable {// counter countdownlatch latch; // component idint ID; // constructor public componentthread (countdownlatch latch, int ID) {This. latch = latch; this. id = ID;} public void run () {// initialize the component system. out. println ("Initializing component" + id); try {thread. sleep (500 x ID);} catch (interruptedexception e) {} system. out. prin TLN ("component" + ID + "initialized! "); // Subtract one latch from the counter. countdown () ;}}/*** start server */public static void startserver () throws exception {system. out. println ("server is starting. "); // initialize a countdownlatchcountdownlatch latch = new countdownlatch (3) with an initial value of 3; // start three threads to start three components: executorservice service = executors. newcachedthreadpool (); service. submit (New componentthread (latch, 1); service. submit (New componentthread (latch, 2); service. submit (New compon Entthread (latch, 3); service. shutdown (); // wait until the initialization of the three components completes latch. await (); // when all three required components are complete, the server can continue the system. out. println ("server is up! ");} Public static void main (string [] ARGs) throws exception {countdownlatchtest. startserver ();}}

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.