CountDownLatch 倒计时闭锁 测试

2023-08-15  本文已影响0人  愤怒的阿昆达
import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {

  static int subThreadNums = 2;
  static CountDownLatch countDownLatch = new CountDownLatch(subThreadNums);

  public static void main(String[] args) throws InterruptedException {
    System.out.println("start main thread...");

    new Thread(() -> {
      System.out.println("thread-1 running...");
      for (int i = 10; i > 0; i--) {
        try {
          System.out.println("thread-1 running..." + i + "秒...");
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
      System.out.println("thread-1 over...");
      countDownLatch.countDown();
    }).start();

    new Thread(() -> {
      System.out.println("thread-2 running...");
      for (int i = 5; i > 0; i--) {
        try {
          System.out.println("thread-2 running..." + i + "秒...");
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
      }
      System.out.println("thread-2 over...");
      countDownLatch.countDown();
    }).start();

    System.out.println("waiting for sub threads...");
    countDownLatch.await();

    System.out.println("continue main thread...");
  }


}
image.png
上一篇 下一篇

猜你喜欢

热点阅读