Java Reference
In-Depth Information
Listing 6-42. A Class to Represent the Main Service That Depends on Helper Services to Start
// LatchMainService.java
package com.jdojo.threads;
import java.util.concurrent.CountDownLatch;
public class LatchMainService extends Thread {
private CountDownLatch latch;
public LatchMainService(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();
}
}
}
Listing 6-43 lists a program to test the concept of helper and main services with a latch. You create a latch that
is initialized to two. The main service thread is started first and it calls latch's await() method to wait for the helper
service to start. Once both helper threads call the countDown() method of the latch, the main service starts. The
output explains the sequence of events clearly.
Listing 6-43. A Class to Test the Concept of a Latch with Helper and Main Services
// LatchTest.java
package com.jdojo.threads;
import java.util.concurrent.CountDownLatch;
public class LatchTest {
public static void main(String[] args) {
// Create a countdown latch with 2 as its counter
CountDownLatch latch = new CountDownLatch(2);
// Create and start the main service
LatchMainService ms = new LatchMainService(latch);
ms.start();
Search WWH ::




Custom Search