一。
1>CountDownLatch简介
CountDownLatch是一个计数器,它有一个初始数,等待这个计数器的线程必须等到计数器数到0时才可以执行、
和join方法有相似之处
2>测试代码如下。重点在被注释那两行,比较注释与否的差别就明白其作用了
public class CountDownLatchTest {
public static class ComponentThread implements Runnable{
CountDownLatch latch;
int ID;
public ComponentThread(CountDownLatch latch,int id){
this.latch=latch;
this.ID=id;
}
@Override
public void run() {
System.out.println("initializing component"+ID);
try {
Thread.sleep(ID*2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("component "+ID+" initialed");
latch.countDown();
}
}
public static void startServer() throws Exception{
System.out.println("server starting");
CountDownLatch latch=new CountDownLatch(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();
// latch.await();
System.out.println("servier is up");
}
public static void main(String[] args) {
try {
startServer();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}