CountDownLatch 工具类可以初始一个计数值,在计数值为0之前,可以使用 await() 方法进行阻塞,调用countDown() 方法该计数值减1。应用场景:一项大的工作,分成5份,计数值初始为5,每下载好一份,计数值减1,5份全部下好,计数值为0,开始执行await()之后的操作。
1. 概述
构造函数,初始计数值为 count :public CountDownLatch(int count)
等待计数器为0,否则进行阻塞:public void await()
等待一定时间,计数器为0或者超时则不在阻塞:public boolean await(long timeout, TimeUnit unit)
计数器减一:public void countDown()
获取当前计数值:public long getCount()
2. 测试样例
计数值初始为 2 。
package util;import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;public class CountDownLatchStudy implements Runnable {public static CountDownLatch countDownLatch = new CountDownLatch(2);public static void main(String[] args) {new Thread(new CountDownLatchStudy()).start();try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(3);}@Overridepublic void run() {System.out.println("step1");try {TimeUnit.MILLISECONDS.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}countDownLatch.countDown();System.out.println("step2");try {TimeUnit.MILLISECONDS.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}countDownLatch.countDown();}
}
运行截图:
计数值初始设置为 3(其他代码不变)。则会一直阻塞:
public static CountDownLatch countDownLatch = new CountDownLatch(3);
一直阻塞,运行截图:
超时等待,修改await(),计数保持为3:
countDownLatch.await(5000, TimeUnit.MILLISECONDS);
会先阻塞,运行截图:
然后超时退出阻塞,运行截图:
参考文献:
- Java并发编程的艺术 / 方腾飞,魏鹏,魏晓明著 . ——北京:机械工业出版社,2015.7