CountDownLatch是什么
CountDownLatch是一个同步工具类,在是jdk1.5新加入的一个包,用来解决并发编程的线程安全的问题
方法详解
- CountDownLatch(int count):count为计数器的初始值(一般需要多少个线程执行,count就设为几)。
- countDown(): 每调用一次计数器值-1,直到count被减为0,代表所有线程全部执行完毕。
- getCount():获取当前计数器的值。
- await(): 等待计数器变为0,即等待所有异步线程执行完毕。
- boolean await(long timeout, TimeUnit unit): 此方法与await()区别:
- 1:此方法至多会等待指定的时间,超时后会自动唤醒,若 timeout 小于等于零,则不会等待
- 2:boolean 类型返回值:若计数器变为零了,则返回 true;若指定的等待时间过去了,则返回 false
应用场景
- 多线程上传下载
- 某个线程需要在其他n个线程执行完毕后再向下执行
代码示例
class DemoApplicationTests {
@Test
void contextLoads() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new Thread(new demo(countDownLatch,i)).start();
}
// countDownLatch.await();
boolean await = countDownLatch.await(3L, TimeUnit.SECONDS);
System.out.println(countDownLatch.getCount());
if(await){
System.out.println("执行完毕了");
}else {
System.out.println("没有执行完");
}
}
class demo implements Runnable{
private CountDownLatch countDownLatch;
private Long i;
public demo(CountDownLatch countDownLatch,long i) {
this.countDownLatch = countDownLatch;
this.i=i;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行了");
try {
Thread.sleep(i*1000L);
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName()+":"+countDownLatch.getCount());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
评论区