Java thread concurrency Countdownlatch class use example _java

Source: Internet
Author: User
Tags static class

Copy Code code as follows:

Package Com.yao;

Import Java.util.concurrent.CountDownLatch;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

/**
* Countdownlatch is a counter, it has an initial number,
* The thread waiting for this counter must wait until the counter countdown to 0 o'clock to continue.
*/
public class Countdownlatchtest {

/**
* Initialize the thread of the component
*/
public static class Componentthread implements Runnable {
Counter
Countdownlatch latch;
Component ID
int ID;

Construction method
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 (+ ID);
  &NBSP} catch (Interruptedexception e) {
   }
    System.out.println ("Component" + ID + "initialized!");
   //The counter by one
   latch.countdown ();
 &NBSP}
 }

/**
* Start the server
*/
public static void StartServer () throws Exception {
System.out.println ("Server is starting.");
Initializes a countdownlatch with an initial value of 3
Countdownlatch latch = new Countdownlatch (3);
3 Threads to start 3 components separately
Executorservice service = Executors.newcachedthreadpool ();
Service.submit (new Componentthread (latch, 1));
Service.submit (new Componentthread (latch, 2));
Service.submit (new Componentthread (latch, 3));
Service.shutdown ();

Waiting for initialization of 3 components is complete
Latch.await ();

When the required three components are complete, the server can continue
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.