Example of using the countdownlatch class with concurrent Java threads

  • 2020-04-01 02:49:03
  • OfStack


package com.yao;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {
 
 public static class ComponentThread implements Runnable {
  //counter
  CountDownLatch latch;
  //Component ID
  int ID;
  //A constructor
  public ComponentThread(CountDownLatch latch, int ID) {
   this.latch = latch;
   this.ID = ID;
  }
  public void run() {
   //Initialize component
   System.out.println("Initializing component " + ID);
   try {
    Thread.sleep(500 * ID);
   } catch (InterruptedException e) {
   }
   System.out.println("Component " + ID + " initialized!");
   //Subtract one from the counter
   latch.countDown();
  }
 }
 
 public static void startServer() throws Exception {
  System.out.println("Server is starting.");
  //Initializes an CountDownLatch with an initial value of 3
  CountDownLatch latch = new CountDownLatch(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 ComponentThread(latch, 3));
  service.shutdown();
  //Wait for the initialization of all three components to complete
  latch.await();
  //When all three required components are complete, Server can proceed
  System.out.println("Server is up!");
 }
 public static void main(String[] args) throws Exception {
  CountDownLatchTest.startServer();
 }
}


Related articles: