1 案例介绍
在日常开发中经常会遇到需要在主线程中开启多 线程去并行执行任务 并且主线程需要等待所有子线程执行完 后再进行汇总的场景。在 CountDownL tch 出现之前一般都使用线程的 join () 方法来实现这一点,但是 join 方法不够灵活 不能够满足不同场景的需要,所以 JDK 开发组提供了 ountDo nLatch 这个类。
demo1:
public class CountDownLatchTest {public static void main(String[] args) throws InterruptedException {CountDownLatch latch = new CountDownLatch(5);ConcurrentHashMap cMap = new ConcurrentHashMap();for (int i = 0; i < 5; i++) {int finalI = i;Thread t = new Thread(new Runnable() {@Overridepublic void run() {cMap.put("key" + finalI, finalI);System.out.println(finalI);latch.countDown();System.out.println("latch.getCount():"+latch.getCount());}});t.start();}latch.await();System.out.println("最后latch.getCount():"+latch.getCount());System.out.println("map大小:" + cMap.size());}}
输出:
0latch.getCount():41latch.getCount():32latch.getCount():24latch.getCount():13latch.getCount():0最后latch.getCount():0map大小:5
demo2:
public class CountDownLatchTest2 {public static void main(String[] args) throws InterruptedException {CountDownLatch latch = new CountDownLatch(2);Thread t = new Thread(new Runnable() {@Overridepublic void run() {try {System.out.println("子线程sleep 5s");Thread.sleep(5000);System.out.println("子线程运行结束");latch.countDown();} catch (InterruptedException e) {e.printStackTrace();}}});Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {try {System.out.println("子线程2 sleep 3s");Thread.sleep(3000);System.out.println("子线程2运行结束");latch.countDown();} catch (InterruptedException e) {e.printStackTrace();}}});Thread mainThtead = new Thread(new Runnable() {@Overridepublic void run() {try {System.out.println("主线程sleep 1s");Thread.sleep(1000);System.out.println("主线程运行结束");} catch (InterruptedException e) {e.printStackTrace();}System.out.println("这是一个主线程,todo...");}});t.start();t2.start();latch.await();mainThtead.start();}}
输出:
子线程sleep 5s子线程2 sleep 3s子线程2运行结束子线程运行结束主线程sleep 1s主线程运行结束这是一个主线程,todo...
注释掉CountDownLatch输出:
子线程2 sleep 3s主线程运行结束这是一个主线程,todo...子线程2运行结束子线程运行结束
