CountDownLatch是一个同步协助类,允许一个或多个线程等待,直到其他线程完成,才会往下执行。
CountDownLatch和Thread.join的区别:
1、join的实现是不停的去监测join线程是否存活,如果join线程存活就让当前线程等待
2、CountDownLatch是调用count.countDown();方法使计数器减一
CountDownLatch和CyclicBarrier(回环栅栏)的区别:
1、CountDownLatch不可以复用,而CyclicBarrier的计数器达到0时,会重置,达到复用的效果
2、CountDownLatch会阻塞主线程、CyclicBarrier不会阻塞主线程。
3、CountDownLatch是用AQS来实现的,CyclicBarrier是用ReentrantLock和Conditon实现阻塞和唤醒。
4、CountDownLatch是等待其他线程执行完,在执行剩下的,CyclicBarrier是多个线程执行完之后,在同时执行。
CountDownLatch的简单使用
package com.example.juc.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchTest {
private static Map map = new HashMap();
public static void main(String[] args) {
CountDownLatch count = new CountDownLatch(3);
Thread thread1 = new Thread(() -> {
map.put("a", "a");
count.countDown();
});
Thread thread2 = new Thread(() -> {
map.put("b", "b");
count.countDown();
});
Thread thread3 = new Thread(() -> {
try {
map.put("c", "c");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count.countDown();
});
thread1.start();
thread2.start();
thread3.start();
try {
count.await();
map.forEach((k, v) -> {
System.out.println("k:" + k + ",v:" + v);
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}