CountDownLatch

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/** 
* @Title: Project.java 
* @Package 
* @Description: 
* @author 任伟 
* @date 2015年1月29日 下午5:36:11 
* @version V1.0 
*/

/**
* @ClassName: Project
* @Description:模拟项目的开发,只有当每个模块都完成后,项目才完成 每个模块的用时不同
* @author 任伟
* @date 2015年1月29日 下午5:36:11
*/
public class Project {
static final int SIZE = 20;

public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(); // 线程池(缓存型池子)
CountDownLatch latch = new CountDownLatch(SIZE); // 门闩
Controller controller = new Controller(latch);
exec.execute(controller);
Random r = new Random(); 
for (int i = 0; i < SIZE; i++) {
exec.execute(new Module(latch, "模块" + (i + 1), r.nextInt(2000)));
}
exec.shutdown();
}
}

class Module implements Runnable {
private CountDownLatch latch;
private String moduleName;
private int time;

/**
* @param latch
* @param moduleName
* @param time
*/
public Module(CountDownLatch latch, String moduleName, int time) {
super();
this.latch = latch;
this.moduleName = moduleName;
this.time = time;
}

@Override
public void run() {
try {
work();
latch.countDown();// 调用了 countDown() 方法,在当前计数到达零之前,await 方法会一直受阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private void work() throws InterruptedException {
TimeUnit.MICROSECONDS.sleep(time);
System.out.println(moduleName + "完成,耗时:" + time);

}

}

class Controller implements Runnable {
private CountDownLatch latch;

public Controller(CountDownLatch latch) {
super();
this.latch = latch;
}

@Override
public void run() {
try {
latch.await();
System.out.println("所有模块都完成,任务完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

  当await(),当前线程阻塞,直到CountDownLatch=0被唤醒

       countDown(),CountDownLatch-1

原文地址:https://www.cnblogs.com/renwei/p/4260567.html