首页 > 其他分享 >CountDownLatch的用法

CountDownLatch的用法

时间:2023-03-16 19:34:23浏览次数:36  
标签:Thread await .... 阻塞 用法 线程 CountDownLatch

CountDownLatch的两个重要方法::await()与countDown()

  • await():调用await()方法的线程会被封装成共享节点加入同步队列阻塞等待,直至state=0时才会唤醒同步队列中所有的线程
  • countDown():调用countDown()方法的线程会对state减一

而关于CountDownLatch有两种用法:

  • 一、多等一:初始化count=1,多条线程await()阻塞,一条线程调用countDown()唤醒所有阻塞线程
  • 二、一等多:初始化count=x,多线程countDown()对count进行减一,一条线程await()阻塞,当count=0时阻塞的线程开始执行

1. 使用CountDownLatch阻塞线程,让多个线程同时执行,可用于模拟并发场景

```

@Test
public void test1() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i = 1; i <= 3; i++) {
new Thread(() -> {
try {
System.out.println("线程:" + Thread.currentThread().getName()
+ "....阻塞等待!");
countDownLatch.await();
// 可以在此处调用需要并发测试的方法或接口
System.out.println("线程:" + Thread.currentThread().getName()
+ "....开始执行!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "T" + i).start();
}
Thread.sleep(1000);
countDownLatch.countDown();
System.out.println("1111");
}

```

输出结果:

```

线程:T1....阻塞等待!
线程:T2....阻塞等待!
线程:T3....阻塞等待!
1111
线程:T2....开始执行!
线程:T3....开始执行!
线程:T1....开始执行!

```

2. 使用CountDownLatch阻塞主线程,让多个线程执行后进入等待状态,直到最后一个执行完,主线程才结束,

```

@Test
public void test2() throws InterruptedException {
final CountDownLatch countDownLatch = new CountDownLatch(3);
for (int i = 1; i <= 3; i++) {
new Thread(() -> {
System.out.println("线程:" + Thread.currentThread().getName()
+ "....阻塞等待!");
// 可以在此处调用需要并发测试的方法或接口
System.out.println("线程:" + Thread.currentThread().getName()
+ "....开始执行!");
countDownLatch.countDown();
}, "T" + i).start();
}
Thread.sleep(1000);
countDownLatch.await();
System.out.println("1111");
}

```

执行结果:

```

线程:T1....阻塞等待!
线程:T1....开始执行!
线程:T2....阻塞等待!
线程:T2....开始执行!
线程:T3....阻塞等待!
线程:T3....开始执行!
1111

```

标签:Thread,await,....,阻塞,用法,线程,CountDownLatch
From: https://www.cnblogs.com/wanthune1/p/17223885.html

相关文章