功能:保持一个或多个线程等待(CountDownLatch的await方法)直到CountDownLatch计数为0(调用CountDownLatch的countDown方法)时才开启等待的线程。
例如:学校的期末考试有10科,只有当每一科都结束后才能够汇总成绩。CountDownLatch正适合这样的需求,在汇总成绩时一直await,知道CountDownLatch计数到0为止,表明所有考试都已经结束,现在可以汇总了。具体代码如下:
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- class Exam implements Runnable {
- private CountDownLatch latch;
- private String name;
- public Exam(CountDownLatch latch, String name) {
- this.latch = latch;
- this.name = name;
- }
- @Override
- public void run() {
- computeKPI();
- }
- public void computeKPI() {
- try {
- TimeUnit.MILLISECONDS.sleep(10);
- System.out.println(this + " is done");
- } catch (InterruptedException e) {
- System.out.println(e);
- }
- latch.countDown();
- }
- public String toString() {
- return name;
- }
- }
- class AddAll implements Runnable {
- private CountDownLatch latch;
- private String name;
- public AddAll(CountDownLatch latch, String name) {
- this.latch = latch;
- this.name = name;
- }
- @Override
- public void run() {
- computeKPI();
- }
- public void computeKPI() {
- try {
- System.out.println(this + "is waiting");
- latch.await();
- } catch (InterruptedException e) {
- System.out.println(e);
- }
- System.out.println(this + "is done");
- }
- public String toString() {
- return name;
- }
- }
- public class CountDownLatchDemo2 {
- public static void main(String[] args) {
- ExecutorService exec = Executors.newCachedThreadPool();
- CountDownLatch latch = new CountDownLatch(10);
- for (int i = 0; i < 10; i++) {
- exec.execute(new Exam(latch, "科目" + i));
- }
- exec.execute(new AddAll(latch, "汇总"));
- exec.shutdown();
- }
- }
最后的打印结果如下:
汇总is waiting
科目1 is done
科目9 is done
科目7 is done
科目2 is done
科目0 is done
科目6 is done
科目3 is done
科目4 is done
科目8 is done
科目5 is done
汇总is done
结果可能会略有不同,但是汇总成绩总是在最后的
本文介绍了并发编程中CountDownLatch的使用场景和实现原理,通过一个期末考试汇总成绩的例子,展示了如何利用CountDownLatch确保所有任务完成后执行后续操作。具体代码包括自定义的Exam和AddAll类,以及CountDownLatchDemo2类的实现。
731

被折叠的 条评论
为什么被折叠?



