JAvaスレッド同時countdownlatchクラス使用例
package com.yao;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* CountDownLatch , ,
* 。
*/
public class CountDownLatchTest {
/**
*
*/
public static class ComponentThread implements Runnable {
//
CountDownLatch latch;
// ID
int ID;
//
public ComponentThread(CountDownLatch latch, int ID) {
this.latch = latch;
this.ID = ID;
}
public void run() {
//
System.out.println("Initializing component " + ID);
try {
Thread.sleep(500 * ID);
} catch (InterruptedException e) {
}
System.out.println("Component " + ID + " initialized!");
//
latch.countDown();
}
}
/**
*
*/
public static void startServer() throws Exception {
System.out.println("Server is starting.");
// 3 CountDownLatch
CountDownLatch latch = new CountDownLatch(3);
// 3 3
ExecutorService service = Executors.newCachedThreadPool();
service.submit(new ComponentThread(latch, 1));
service.submit(new ComponentThread(latch, 2));
service.submit(new ComponentThread(latch, 3));
service.shutdown();
// 3
latch.await();
// ,Server
System.out.println("Server is up!");
}
public static void main(String[] args) throws Exception {
CountDownLatchTest.startServer();
}
}