当前位置:网站首页>【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
2022-07-02 09:38:00 【老衲の少女心】
假装很多文字,直接看代码,每行注释小白也不怕,可以自适应修改
重要的事情在提醒一句,多线程大多数报错,或者数据对不上,请检查线程池的拒绝策略
// 原子计数器,很多时候不确定到底需要执行多少次防止出错
private static final AtomicInteger atomicInteger = new AtomicInteger(0);
// 线程配置,阻塞队列,策略模式都配置合理,可以保证线程不会丢失数据
// 其他线程池参数,可以根据自己需要修改,对应参数不懂的可以看我另外一篇文章
//【多线程】ThreadPoolExecutor类万字源码解析(注解超级详细)
// 自行根据需要修改池子大小即可
private static final ExecutorService pool = new ThreadPoolExecutor(2, 4,
1000, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(100),
new ThreadPoolExecutor.CallerRunsPolicy());
// Future接口具有阻塞同步性,这样的代码运行效率会大打折扣
// 接口CompletionService 可以解决这样的问题。
private static final CompletionService<Integer> completionService = new ExecutorCompletionService<>(pool);
public static void main(String[] args) {
// 开始执行
System.out.println(new Date());
//开始计时
for (int i = 0; i < 3; i++) {
// 计数器加1
atomicInteger.getAndIncrement();
Callable<Integer> callable = ()-> {
// 子线程执行业务代码
int num = 1000;
int s = 0;
for (int j = 0; j < num; j++) {
s += j;
}
Thread.sleep(2000);
System.out.println("t Over s =" + s);
// 返回执行结果
return s;
};
try {
// 执行速度太快看不出效果,睡一会
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 执行任务
completionService.submit(callable);
}
// 获取原子计数器的值,循环获取返回值
for (int i = 0; i < atomicInteger.get(); i++) {
try {
// CompletionService 的take()方法会先返回最早执行完的Callable返回值
// 哪个任务先执行完,哪个任务就先返回值就先打印,不一直等待第一个Callable对象。
// CompletionService接口中如果当前没有任务被执行完
// 则 take(). get() 方法还是呈堵塞特性。
Integer s = completionService.take().get();//需要捕获两种异常
System.out.println("s : " + s);
}catch (InterruptedException | ExecutionException e){
e.printStackTrace();
}
}
// pool.shutdown(); 平缓关闭,不允许新的线程加入,正在运行的都跑完即可关闭。
// pool.shutdownNow(); 暴力关闭。不允许新的线程加入,且直接停到正在进行的线程。
pool.shutdown();
System.out.println(new Date());
}
边栏推荐
- Webauthn - official development document
- 基于Hardhat编写合约测试用例
- Internship report skywalking distributed link tracking?
- How does the whole network display IP ownership?
- C# 文件与文件夹操作
- MySQL comparison operator in problem solving
- QT learning diary 8 - resource file addition
- Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting
- Develop scalable contracts based on hardhat and openzeppelin (II)
- 对毕业季即将踏入职场的年轻人的一点建议
猜你喜欢

Develop scalable contracts based on hardhat and openzeppelin (II)

PLC-Recorder快速监控多个PLC位的技巧

From the perspective of attack surface, see the practice of zero trust scheme of Xinchuang

金山云——2023届暑期实习

【云原生】2.5 Kubernetes 核心实战(下)

PKG package manager usage instance in FreeBSD

JS -- take a number randomly from the array every call, and it cannot be the same as the last time

mmrotate旋转目标检测框架使用记录

MySQL comparison operator in problem solving

Mmrotate rotation target detection framework usage record
随机推荐
对毕业季即将踏入职场的年轻人的一点建议
Wechat applet uses Baidu API to achieve plant recognition
MTK full dump grab
Digital transformation takes the lead to resume production and work, and online and offline full integration rebuilds business logic
高德根据轨迹画线
Develop scalable contracts based on hardhat and openzeppelin (II)
tqdm的多行显示与单行显示
PLC-Recorder快速监控多个PLC位的技巧
Is it safe to open a stock account online? I'm a novice, please guide me
Functional interfaces and method references
基于Hardhat编写合约测试用例
Win11 arm system configuration Net core environment variable
ROS lacks catkin_ pkg
【云原生】2.5 Kubernetes 核心实战(下)
Iii. Système de démarrage et d'horloge à puce
How does the whole network display IP ownership?
PowerBI中导出数据方法汇总
通过券商经理的开户二维码开股票账户安全吗?还是去证券公司开户安全?
III Chip startup and clock system
The first white paper on agile practice in Chinese enterprises was released | complete download is attached