1 创建合适的线程池:
创建线程池方式参考:https://blog.csdn.net/l123lgx/article/details/105731660
本文创建固定线程个数的线程池:
ExecutorService executorService = Executors.newFixedThreadPool(2);
2 定义CountDownLatch:
CountDownLatch countDownLatch = new CountDownLatch(2);
3 定义两个线程的执行结果:
private String resultOne;
private String resultTwo;
4 定义线程执行任务:
executorService.submit(()->{
System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
this.resultOne = "第一个结果";
countDownLatch.countDown();
});
executorService.submit(()->{
System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
this.resultTwo = "第二个结果";
countDownLatch.countDown();
});
executorService.shutdown();
5 任务执行完毕:
try {
countDownLatch.await();
/**
* do some thing
*/
System.out.println("两个子线程都执行完毕,继续执行主线程");
System.out.println(" 得到线程执行结果,testCountDown.getResultOne() = " + this.resultOne);
System.out.println("得到线程执行结果,testCountDown.getResultTwo() = " + this.resultTwo);
} catch (InterruptedException e) {
e.printStackTrace();
throw e;
}
6 完整代码:
package org.lgx.bluegrass.bluegrasscoree.util.tooldemo;
import lombok.Data;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Description TODO
* @Date 2021/12/29 16:56
* @Author lgx
* @Version 1.0
*/
@Data
public class CountDownLatchDemo {
private String resultOne;
private String resultTwo;
public void testCountDownLatch() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(()->{
System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
this.resultOne = "第一个结果";
countDownLatch.countDown();
});
executorService.submit(()->{
System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
this.resultTwo = "第二个结果";
countDownLatch.countDown();
});
executorService.shutdown();
System.out.println("等待两个线程执行完毕…… ……");
try {
countDownLatch.await();
/**
* do some thing
*/
System.out.println("两个子线程都执行完毕,继续执行主线程");
System.out.println(" 得到线程执行结果,testCountDown.getResultOne() = " + this.resultOne);
System.out.println("得到线程执行结果,testCountDown.getResultTwo() = " + this.resultTwo);
} catch (InterruptedException e) {
e.printStackTrace();
throw e;
}
}
public static void main(String[] args) throws InterruptedException {
CountDownLatchDemo testCountDown = new CountDownLatchDemo();
testCountDown.testCountDownLatch();
}
}