CountDownLatch 减少计数
原创
©著作权归作者所有:来自51CTO博客作者wx61cd54ea3a202的原创作品,请联系作者获取转载授权,否则将追究法律责任
问题,中间线程还没走完,最后的线程已经完成
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() + "班长锁门");
}
}