A latch makes a group of threads wait until it reaches its terminal state.
Once a latch reaches its terminal state, it lets all threads pass through.
A latch is a one-time object. It cannot be reset and reused.
CountDownLatch class from the java.util.concurrent package implements the latch.
The following code represents a helper service and a main service, respectively. The
main service depends on helper services to start.
After all helper services have started, only then can the main service start.
import java.util.Random; import java.util.concurrent.CountDownLatch; class HelperTask extends Thread { private int ID; private CountDownLatch latch; public HelperTask(int ID, CountDownLatch latch) { this.ID = ID; this.latch = latch; }//from ww w . java 2s. co m public void run() { try { int startupTime = 3; System.out.println("Service #" + ID + " starting in " + startupTime + " seconds..."); Thread.sleep(startupTime * 1000); System.out.println("Service #" + ID + " has started..."); } catch (InterruptedException e) { e.printStackTrace(); } finally { // Count down on the latch to indicate that it has started this.latch.countDown(); } } } class MainTask extends Thread { private CountDownLatch latch; public MainTask(CountDownLatch latch) { this.latch = latch; } public void run() { try { System.out .println("Main service is waiting for helper services to start..."); latch.await(); System.out.println("Main service has started..."); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Main { public static void main(String[] args) { // Create a count down latch with 2 as its counter CountDownLatch latch = new CountDownLatch(2); // Create and start the main service MainTask ms = new MainTask(latch); ms.start(); // Create and start two helper services for (int i = 1; i <= 2; i++) { HelperTask lhs = new HelperTask(i, latch); lhs.start(); } } }