JAVA多线程CountDownLatch倒计时锁应用
发布时间:2020-06-21 23:05:04
来源:51CTO
阅读:361
作者:恋上程序员
package concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Auth: zhouhongliang
* Date:2019/8/1
* CountDownLatch倒计时锁
* 阻塞主线程,等子线程全部执行完之后主线程继续执行
*
*/
public class CountDownLatchDemo {
public static int count = 0;
/**
* 计算1至10000的和
* @param args
*/
public static void main(String[] args) throws InterruptedException {
//定义一个缓冲线程池
ExecutorService executorService = Executors.newCachedThreadPool();
//定义一个倒计时锁
CountDownLatch countDownLatch = new CountDownLatch(10000);
for (int i=1;i<=10000;i++){
final int index = i;
//多个线程执行
executorService.execute(()->{
synchronized (CountDownLatchDemo.class){
try {
count += index;
} catch (Exception e) {
e.printStackTrace();
} finally {
//计数器减1
countDownLatch.countDown();
}
}
});
}
//线程阻塞,知道countDownLatch计数值=0
countDownLatch.await();
System.out.println(count);
//关闭线程池
executorService.shutdown();
}
}
输出结果:50005000