当前位置:
ExecutorService,解决多任务同时进行,并等待全部任务完成再执行主线程<收藏>
机器助手 | 2025-07-13
34人浏览
package com.biemo.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class MyTest {
public static void main(String[] args) {
// 待通知的消息
List<String> notifyMsgList = new ArrayList<String>(10000);
for (int i = 0; i < 100; i++) {
notifyMsgList.add("发工资啦" + i);
}
// 1. 调用 Excutors 类的静态工厂方法创建一个 ExcutorService 对象(线程池);
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Callable<Void>> tasks = new ArrayList<>();
for (int i = 0; i < notifyMsgList.size(); i++) {
int finalI = i;
// 2. 创建 Callable 实现类的实例,作为线程执行任务。
tasks.add(() -> {
if (finalI == 10) {
//故意弄一个异常线程
int a = 100 / 0;
}
System.out.println(Thread.currentThread().getName() + "-->通知:" + notifyMsgList.get(finalI));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
});
}
//获取每个线程执行完的结果
try {
for (Future<Void> future : executorService.invokeAll(tasks)) {
try {
future.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//4. 调用 ExcutorService 对象的 shutdown 方法来关闭线程池。
executorService.shutdown();
}
System.out.println("主线程继续执行。。。。。");
}
}
该文章部分内容已隐藏
