CountDownLatch

2020-05-17  本文已影响0人  龙剑灵

计数器变为0后就永远为0

public static void main(String[] args) {

    //计数器变为0后就永远为0
   //若下面参数设置为4,则程序wait一直处于等待中
    CountDownLatch countDownLatch = new CountDownLatch(3);

    IntStream.range(0,3).forEach(i -> new Thread(() -> {
      try {
        Thread.sleep(2000);
        System.out.println("hello");
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        //计数器变为0后就永远为0
        countDownLatch.countDown();
      }
    }).start());

    System.out.println("启动子线程完毕");

    try {
     // countDownLatch.await();
      countDownLatch.await(1, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("主线程执行结束");

  }
上一篇 下一篇

猜你喜欢

热点阅读