Java CountDownLatch学习记录
CountDownLatch顾名思义通过计数的下降来触发被其标识的线程,可以通过初始话一个CountDownLatch来设置需要等待的线程,如CountDownLatch begin = new CountDownLatch(2); 也就是你可以线程中使用begin.await()来使当前线程阻塞,只有当begin的个数计数变成0,之前设置await的线程才能继续往下面跑! 但是这个计数器的值不可以重置,也就是他初始化一次只能使用一次;如果需要重置可以使用CyclicBarrier。
下面是一个具体的例子(网上取的):
package json;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String args[]) throws InterruptedException {
final CountDownLatch begin = new CountDownLatch(1);
// 结束的倒数锁
final CountDownLatch end = new CountDownLatch(10);
// 十名选手
final ExecutorService exec = Executors.newFixedThreadPool(10);
for (int index = 0; index < 10; index++) {
final int NO = index + 1;
Runnable run = new Runnable() {
public void run() {
try {
begin.await();// 一直阻塞
Thread.sleep((long) (Math.random() * 10000));
System.out.println("No." + NO + "arrived");
} catch (InterruptedException e) {
} finally {
end.countDown();
}
}
};
exec.submit(run);
}
System.out.println("Game Start");
begin.countDown();
end.await();
System.out.println("Game Over");
exec.shutdown();
}
}
输出结果:
Game Start
No.6arrived
No.8arrived
No.3arrived
No.10arrived
No.7arrived
No.4arrived
No.2arrived
No.5arrived
No.1arrived
No.9arrived
Game Over