Java并发程序设计(20)并发锁之倒数锁CountDownLatch
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java并发程序设计(20)并发锁之倒数锁CountDownLatch相关的知识,希望对你有一定的参考价值。
1.1. 倒数锁CountDownLatch
CountDownLatch是另外一种线程同步工具。参与倒数的每个线程在工作完成后都执行countDown()方法,当所有线程都执行完后,会唤醒一个或多个在等待倒数计数为0的线程。
package com.test.concurrence; import java.util.Date; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchTest { public static void main(String[] args) { final CountDownLatch countDownLatch = new CountDownLatch(10); ExecutorService executorService = Executors.newFixedThreadPool(10); //建立10个倒数线程。 for(int i=0;i<10;i++){ executorService.submit(new Runnable(){ @Override public void run() { try { Thread.sleep(1000* new Random().nextInt(20)); } catch (InterruptedException e) { e.printStackTrace(); } //每个参与倒数的线程都倒数1次,计数减1. countDownLatch.countDown(); System.out.println("count:" + countDownLatch.getCount() + " , " + new Date()); } }); } //建立3个等待倒数计数为0的线程。 for(int i=0;i<3;i++){ executorService.submit(new Runnable(){ @Override public void run() { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("ready:" + countDownLatch.getCount() + " , " + new Date()); } }); } executorService.shutdown(); } }
运行结果如下:
count:9 , Sat Mar 18 23:11:16 CST 2017
count:7 , Sat Mar 18 23:11:18 CST 2017
count:8 , Sat Mar 18 23:11:18 CST 2017
count:6 , Sat Mar 18 23:11:20 CST 2017
count:5 , Sat Mar 18 23:11:25 CST 2017
count:4 , Sat Mar 18 23:11:25 CST 2017
count:3 , Sat Mar 18 23:11:26 CST 2017
count:2 , Sat Mar 18 23:11:27 CST 2017
count:1 , Sat Mar 18 23:11:33 CST 2017
count:0 , Sat Mar 18 23:11:33 CST 2017
ready:0 , Sat Mar 18 23:11:33 CST 2017
ready:0 , Sat Mar 18 23:11:33 CST 2017
ready:0 , Sat Mar 18 23:11:33 CST 2017
以上是关于Java并发程序设计(20)并发锁之倒数锁CountDownLatch的主要内容,如果未能解决你的问题,请参考以下文章
Java并发程序设计(12)并发锁之可重入锁ReentrantLock
Java并发程序设计(21)并发锁之交换器Exchanger