想实现六个同学离开教室后,班长关门
错误写法
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <=6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"号同学离开教室了");
},String.valueOf(i)).start();
}
System.out.println("班长锁门了");
}
}
效果如下

正确做法(countDownLatch)
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(6);
for (int i = 1; i <=6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"号同学离开教室了");
//计数 -1
latch.countDown();
},String.valueOf(i)).start();
}
//等待
latch.await();
System.out.println("班长锁门了");
}
}
效果如下
