CountDownLatch,是线程同步辅助类,在一组执行线程中有未完成的线程时,可以让已完成的线程一直等待其他线程完成。设计理念有点类似于团队爬山,前队等后队,人到齐后才算爬山任务完成。
下面的例子模仿有两个人abtest和unittest,两个人跑步,只有两个人都跑完后,才是真正的跑步结束,才打印跑步结束语句,所以打印跑步结束语句的动物要在两个人(线程)跑完步动作之后。
/**
* Description
*
* @author usr1999 2015-1-13
*/
public class CountDownLatchDemo2 {
/**
*
*/
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(2);
Runner run1 = new Runner("abtest", 3000, latch);
Runner run2 = new Runner("unittest", 5000, latch);
ExecutorService exec = Executors.newFixedThreadPool(2);
exec.submit(run1);
exec.submit(run2);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("abtest and unittest completed running");
exec.shutdown();
}
}
class Runner implements Runnable {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String name;
int time;
CountDownLatch latch;
public Runner(String name, int time, CountDownLatch latch) {
this.name = name;
this.time = time;
this.latch = latch;
}
@Override
public void run() {
System.out.println(name + " is ready to run at "
+ sdf.format(new Date()));
doRun();
System.out.println(name + " has runed at " + sdf.format(new Date()));
latch.countDown(); // 计数递减
}
private void doRun() {
try {
TimeUnit.MILLISECONDS.sleep(time);
// Thread.sleep(time);
} catch (InterruptedException e) {
System.out.println(e.getStackTrace());
}
}
}
CountDownLatch主要有三个方法:
CountDownLatch(int count),构造函数,参数为计数的数目。
countDown(), 计数递减,如果计数减到0,则释放所有等待状态的线程。
await(), 线程阻塞方法,使当前线程在计数变为0之前一直等待,直到count值为0才继续执行。