话不多说上代码:
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"上完自习,离开教室");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "*********班长最后关门走人");
}
}
打印结果:
其实这个对象就是模拟一个计数器的效果,如果计数器减到0(countDownLatch.countDown();
每次减一)那么则可以运行,如果没有,那么就会在countDownLatch.await();处一直等待。