问题,中间线程还没走完,最后的线程已经完成

public class Problem {
public static void main(String[] args){
//问题,中间线程还没走完,最后的线程已经完成
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "同学离开");
}, String.valueOf(i)).start();
}
System.out.println(Thread.currentThread().getName() + "班长锁门");
}
}

解决方案,用 CountDownLatch 减少计数

public class Solution {
public static void main(String[] args) throws InterruptedException {
//创建CountDownLatch,设置初始值
CountDownLatch countDownLatch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "同学离开");
//计数减一
countDownLatch.countDown();
}, String.valueOf(i)).start();
}
//等待
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "班长锁门");
}
}