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了,则开始向下的操作
当你发现自己的才华撑不起野心时,就请安静下来学习吧