其他分享
首页 > 其他分享> > JUC辅助类CountDownLatch

JUC辅助类CountDownLatch

作者:互联网

想实现六个同学离开教室后,班长关门

错误写法
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("班长锁门了");
    }
}

效果如下

标签:JUC,辅助,String,System,CountDownLatch,println,public,out
来源: https://www.cnblogs.com/swifties270/p/16124901.html