The code copy is as follows:
package com.yao;
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 counter counts to zero before continuing.
*/
public class CountDownLatchTest {
/**
* The thread that initializes the component
*/
public static class ComponentThread implements Runnable {
// Counter
CountDownLatch latch;
// Component ID
int ID;
// Construct 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(500 * ID);
} catch (InterruptedException e) {
}
System.out.println("Component " + ID + " initialized!");
//Decrement the counter by one
latch.countDown();
}
}
/**
* Start the server
*/
public static void startServer() throws Exception {
System.out.println("Server is starting.");
//Initialize a CountDownLatch with an initial value of 3
CountDownLatch latch = new CountDownLatch(3);
//Start 3 threads to start 3 components respectively
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 the initialization of 3 components to be completed
latch.await();
//When all the required three components are completed, the Server can continue
System.out.println("Server is up!");
}
public static void main(String[] args) throws Exception {
CountDownLatchTest.startServer();
}
}