JAVA实现主线程等待所有子线程执行完成再执行
其中:1~3步
public static void main(String[] args) {
try {
log.info(">>>>>>>>>>开始执行所有线程, MainThread【{}】<<<<<<<<<<", Thread.currentThread().getName());
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(50, 100, 10, TimeUnit.MILLISECONDS,
new LinkedTransferQueue<>(), new CustomizableThreadFactory("自定义线程_"), new ThreadPoolExecutor.AbortPolicy()
);
// 1、 需要明确线程数
CountDownLatch countDownLatch = new CountDownLatch(100);
for (int i = 0; i < 100; i++) {
final int a = i;
threadPoolExecutor.execute(() -> {
try {
for (int j = 0; j < 10; j++) {
if (a == 1 && j == 3) {
// 抛出异常
System.out.println(1 / 0);
}
log.info("-----------------------线程【{}】执行完成-----------------------【{}】", Thread.currentThread().getName(), a + "-" + j);
}
} catch (Exception e) {
// catch异常, 不影响主线程
log.error("--------------------------线程【{}】执行失败, 异常信息{}--------------------------", Thread.currentThread().getName(), ExceptionUtils.getStackTrace(e));
e.printStackTrace();
} finally {
// 2、线程数减 1
countDownLatch.countDown();
}
});
}
// 3、阻塞主线程 直至线程数为0
countDownLatch.await();
log.info(">>>>>>>>>>所有线程执行完成, 关闭线程池, MainThread【{}】<<<<<<<<<<", Thread.currentThread().getName());
threadPoolExecutor.shutdown();
} catch (Exception e) {
e.printStackTrace();
} finally {
log.info(">>>>>>>>>>所有线程执行完成, finally执行, MainThread【{}】<<<<<<<<<<", Thread.currentThread().getName());
}
}