CountDownLatch
CountDownLatch
是一个JUC
包下的同步工具 计数器
作用是: 使一个或者多个线程等待其他线程完成后再执行
CountDownLatch(int count)
void await()
boolean await(long timeout, TimeUnit unit)
void countDown()
long getCount()
String toString()
|
示例
public class CountDownLathTest { public static final int DRAGON_BALL_TOTAL_NUM = 7; public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(DRAGON_BALL_TOTAL_NUM);
for (int i = 0; i < 7; i++) { int index = i; new Thread(() -> { System.out.println("收集到第 " + index + "号龙珠!"); countDownLatch.countDown(); }).start(); }
try { countDownLatch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); }
System.out.println("龙珠收集完毕!!! \n" + "召唤神龙!!");
} }
|
由上述代码可见, CountDownLatch
通过计数定义了线程之间的同步关系
JUC
包下所有同步工具离不开ASQ
的框架(不得不感叹Doug Lea教授强大的抽象和设计)