一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。
package com.jiaoshou.concurency.aqs;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author yangkaifei
* @date 2018/12/11 13:38
*/
@Slf4j
public class CountDownLatchExample{
//线程数
private static int threadCount=500;
public static void main(String[] args)throws InterruptedException {
//线程池
ExecutorService exec=Executors.newCachedThreadPool();
//闭锁实例
final CountDownLatch countDownLatch=new CountDownLatch(threadCount);
for (int i =0;i < threadCount; i++){
final int threadNum=i;
exec.execute(
()->{
try {
test(threadNum);
}catch (Exception e) {
e.printStackTrace();
log.info("出现异常");
}finally {
countDownLatch.countDown();//减一操作
}
});
}
//countDownLatch等于0,线程池执行完毕在执行以下语句。超过这个时间也不执行
countDownLatch.await(10,TimeUnit.MILLISECONDS);
log.info("完成");
exec.shutdown();//关闭线程池
}
private static void test(int number) {
log.info("number:{}",number);
}
}
网友评论