这里只介绍CountDownLatch的使用和场景,源码后期再分解
CountDownLatch实际上是一个程序计数器,初始化一个数值,让一组线程去跑,其他线程处于等待中,跑的那组线程每跑完一个计数器减一,直到计数器为零,此时,等待的线程就可以跑了。计数器不可重复使用。
CountDownLatch api 中三个方法 :
public void await() //线程调用被挂起,计数器为0时执行
public boolean await(long timeout, TimeUnit unit) //线程调用被挂起一段时间后,即使计数器仍不为0时,也执行
public void countDown() //计数器减一操作
简单是代码实例:
public class MyCountDownLatch {
public static void main(String[] args) {
CountDownLatch c = new CountDownLatch(2);//初始化计数器为2
ExecutorService e = Executors.newFixedThreadPool(3);
e.submit(()->{
try {
c.await();//线程一挂起等待执行
System.out.println("Thread-"+Thread.currentThread().getName()+"等待的线程执行");
} catch (Exception e1) {
e1.printStackTrace();
}
});
e.submit(()->{
try {
Thread.sleep(2000);
System.out.println("Thread-"+Thread.currentThread().getName()+"计数线程执行");
c.countDown();//线程2执行完计数器减1
} catch (Exception e1) {
e1.printStackTrace();
}
});
e.submit(()->{
try {
Thread.sleep(2000);
System.out.println("Thread-"+Thread.currentThread().getName()+"计数线程执行");
c.countDown();//线程3执行完计数器减1
} catch (Exception e1) {
e1.printStackTrace();
}
});
}
}
执行结果:
这里使用的jdk1.8的写法()->