CountDownLatch
相关文章:
使用场景:
一个或N个线程,等待其它线程完成某项操作之后才能继续往下执行。CountDownLatch描述的是,一个或N个线程等待其他线程的关系。
使用方法:
- 设CountDownLatch个数:CountDownLatch countDownLatch=new CountDownLatch(3);
- 在等待线程中await:countDownLatch.await();
- 在其他线程中减少count值:countDownLatch.getCount();
- 一旦其他线程中的countDownLatch.getCount()的次数为实例化时的count值,就唤醒等待线程
/**
* 作者:jtl
* 日期:Created in 2019/7/29 14:59
* 描述:CountDownLatch 例子
* 更改:
*/
class CountDownLatchExample {
private static final int total=200;
public static void main(String[] args) throws InterruptedException{
ExecutorService executorService = Executors.newCachedThreadPool();
CountDownLatch countDownLatch=new CountDownLatch(total);
for (int i=0;i<total;i++){
final int threadNum=i;
executorService.execute(()-> {
test(threadNum,countDownLatch.getCount());
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println("CountDownLatch --- finish:"+countDownLatch.getCount());
executorService.shutdown();
}
private static void test(int time,long count){
System.out.println(time+" --- "+count);
}
}
网友评论