美文网首页
CountDownLatch 倒计时闭锁 测试

CountDownLatch 倒计时闭锁 测试

作者: 愤怒的阿昆达 | 来源:发表于2023-08-15 14:56 被阅读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

相关文章

网友评论

      本文标题:CountDownLatch 倒计时闭锁 测试

      本文链接:https://www.haomeiwen.com/subject/dyuhmdtx.html