countdownlatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完毕再执行。从 命名可以解读到countdown是倒数的意思,类似于我们倒计时的概念。
countdownlatch提供了两个方法,一个是countDown,一个是await, countdownlatch初始化的时候需要传入一 个整数,在这个整数倒数到0之前,调用了await方法的程序都必须要等待,然后通过countDown来倒数
package com.example.demo.morethread;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) {
CountDownLatch countDownLatch=new CountDownLatch(3);
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"开始执行"+countDownLatch.getCount());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName()+"执行结束"+countDownLatch.getCount());
},"thread1").start();
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"开始执行"+countDownLatch.getCount());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName()+"执行结束"+countDownLatch.getCount());
},"thread2").start();
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"开始执行"+countDownLatch.getCount());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName()+"执行结束"+countDownLatch.getCount());
},"thread3").start();
try {
countDownLatch.await();
System.out.println("所有线程执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果如下:
使用场景
1. 通过countdownlatch实现最大的并行请求,也就是可以让N个线程同时执行
2. 比如应用程序启动之前,需要确保相应的服务已经启动