CyclicBarrier可以重复使用,而CountdownLatch不能重复使用。
countDownLatch这个类使一个线程等待其他线程各自执行完毕再执行。
是通过一个计数器来实现的,计数器的初始值是线程的数量。通过countDown()来减一,等减到0,await()方法就进入等待run状态。
例子:
public static CountDownLatch countDownLatch = new CountDownLatch(3);
public static void doCountDownLatch(){
Thread t1 = new Thread(() -> {
try {
System.out.println("进入T1 await中!");
countDownLatch.await();
System.out.println("T1 Complete!");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 3; i++) {
System.out.println("进入T2!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
System.out.println("T2 Complete --: " + (3 - i));
}
});
t1.start();
t2.start();
}