一、前言:
首先,在前面我们在学习线程间通信的时候,学到一个关键字:join,例如在main方法中,执行t1.join(),t2.join(),则main主线程会阻塞运行,直到t1,t2分别执行完,回调阻塞在t1,t2上面的线程。这是main线程会重新获得执行契机。
今天咱们学习的CountDownLatch,是非常有用的开发工具类,在JDK1.5版本中,开发包,提供了CountDownLatch也可以实现join的功能,并且比join支持的功能更多,它允许一个或多个线程等待其他线程完成操作。
二、案例分享:
咱们先从案例分析:
package com.jason.thread.tool.countdownlatch;
import java.util.concurrent.CountDownLatch;
/**
* @program: JasonSpringMybatis
* @description
* @author: 大龄程序猿
* @create: 2020-05-30 23:51
**/
public class App {
public static int maxSize=3;
public static CountDownLatch countDownLatch=new CountDownLatch(maxSize);
public static void main(String[] args) throws InterruptedException {
System.out.println("等待线程计数器:"+countDownLatch.getCount());
Thread t_main=new Thread(){
@Override
public void run() {
countDownLatch.countDown();//通知AQS更新state状态值减一。
/*
后续还有其他业务逻辑,需要处理,不像join指令,需要等待当前线程消亡,由JVM通知等待在该线程上的线程。
*/
}
};
t_main.setName("t_main");
Thread t_main1=new Thread(){
@Override
public void run() {
countDownLatch.countDown();
}
};
t_main1.setName("t_main1");
Thread t_main2=new Thread(){
@Override
public void run() {
countDownLatch.countDown();
}
};
t_main.start();
Thread.sleep(1000);
System.out.println("等待线程计数器:"+countDownLatch.getCount());