当前位置:网站首页>【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
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());
}
边栏推荐
- Internship report skywalking distributed link tracking?
- vant tabs组件选中第一个下划线位置异常
- 念念不忘,必有回响 | 悬镜诚邀您参与OpenSCA用户有奖调研
- Is the Ren domain name valuable? Is it worth investing? What is the application scope of Ren domain name?
- Never forget, there will be echoes | hanging mirror sincerely invites you to participate in the opensca user award research
- Principle of scalable contract delegatecall
- 接口调试工具概论
- 高德根据轨迹画线
- deepTools对ChIP-seq数据可视化
- mysql 基本语句
猜你喜欢

Redis exceeds the maximum memory error oom command not allowed when used memory & gt; ' maxmemory'

微信小程序利用百度api达成植物识别

What are the software product management systems? Inventory of 12 best product management tools

III Chip startup and clock system

A white hole formed by antineutrons produced by particle accelerators

基于Hardhat和Openzeppelin开发可升级合约(二)

Webauthn - official development document

2022 love analysis · panoramic report of digital manufacturers of state-owned enterprises

由粒子加速器产生的反中子形成的白洞

ren域名有价值吗?值不值得投资?ren域名的应用范围有哪些?
随机推荐
MTK full dump grab
Functional interfaces and method references
可升级合约的原理-DelegateCall
从攻击面视角,看信创零信任方案实践
Verilog and VHDL signed and unsigned number correlation operations
II Stm32f407 chip GPIO programming, register operation, library function operation and bit segment operation
Resources读取2d纹理 转换为png格式
Principle of scalable contract delegatecall
CTF record
C# 文件与文件夹操作
Mongodb learning and sorting (condition operator, $type operator, limit() method, skip() method and sort() method)
Jinshanyun - 2023 Summer Internship
Order by injection
Skills of PLC recorder in quickly monitoring multiple PLC bits
金山云——2023届暑期实习
sqlite 修改列类型
From the perspective of attack surface, see the practice of zero trust scheme of Xinchuang
STM32单片机编程学习
Verilog 和VHDL有符号数和无符号数相关运算
RPA advanced (II) uipath application practice