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了,则开始向下的操作
上一篇:多线程应用案例


下一篇:前端知识体系:JavaScript基础-作用域和闭包-闭包的实现原理和作用以及堆栈溢出和内存泄漏原理和相应解决办法