CountDownLatch:门阀
构造方法:
// count为门阀数,必须大于0,否则抛出异常
CountDownLatch countDownLatch = new CountDownLatch(int count);
举个例子:在运动会上短跑比赛的时候,有8个运动员和一个裁判,把裁判当做主线程,只有等8个运动员全部完成比赛,有成绩之后,才能做出统计,完成后面的操作(调用await方法),每个运动员到达终点,都会调用(countdown方法),使门阀数减一,当8个运动员全部到终点的时候,门阀数为0,此时裁判员才能继续往下执行
主要方法:
countDownLatch.awati()方法:
调用这个方法的线程会等到构造方法传入的 count 减到 0 的时候,才能继续往下执行;
countDownLatch.countdown()方法:
每次调用,构造方法传入的count数就会减1
使用场景:
让所有线程几乎在同一时间内一起工作:
思路:设置一个门阀,其他线程调用await方法等待,让主函数去打开阀门(调用countdown方法),count为0的时候,所有线程就会一起工作
代码:
门阀类:提供需要调用的等待方法,写到一个类里也可以
class JymCountDownLatch {
// 门阀类
private CountDownLatch countDownLatch;
public JymCountDownLatch(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
public void excu(){
try {
// 被上锁的线程,直到 CountDownLatch 的 count 为 0 才继续执行
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
线程类:
class JymCountDownLatchThread implements Runnable{
private JymCountDownLatch jymCountDownLatch;
public JymCountDownLatchThread(JymCountDownLatch jymCountDownLatch) {
this.jymCountDownLatch = jymCountDownLatch;
}
public void run() {
jymCountDownLatch.excu();
System.out.println(Thread.currentThread().getName()+":"+System.currentTimeMillis());
}
}
测试类代码:
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(1);
JymCountDownLatch jymCountDownLatch = new JymCountDownLatch(countDownLatch);
JymCountDownLatchThread jymCountDownLatchThread = new JymCountDownLatchThread(jymCountDownLatch);
for (int i = 0;i<5;i++){
new Thread(jymCountDownLatchThread).start();
}
// 打开阀门
countDownLatch.countDown();
System.out.println("QWQ");
}
结果: