CountDownLatch工具类使用

java.util.concurrent.CountDownLatch类是用来做减法计数器的
Demo如下:
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(8);
        for (int i = 1; i <= 8; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"走了");
                //数量-1
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        /* 等待计数器归零,然后再向下执行 */
        countDownLatch.wait();
        System.out.println("close door");
    }
}
  • new CountDownLatch(8)意思是从8开始递减;
  • countDownLatch.wait()是监听递减值变化,如果到0了,则开始向下的操作
posted @ 2020-05-21 15:49  小小吸血鬼  阅读(228)  评论(0编辑  收藏  举报