当前位置:网站首页>【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
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());
}
边栏推荐
- ros gazebo相关包的安装
- Verilog and VHDL signed and unsigned number correlation operations
- Digital transformation takes the lead to resume production and work, and online and offline full integration rebuilds business logic
- Compilation errors and printout garbled problems caused by Chinese content in vs2019 code
- TIPC Service and Topology Tracking4
- ren域名有价值吗?值不值得投资?ren域名的应用范围有哪些?
- ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
- Tdsql | difficult employment? Tencent cloud database micro authentication to help you
- MySQL basic statement
- VS2019代码中包含中文内容导致的编译错误和打印输出乱码问题
猜你喜欢
How does the whole network display IP ownership?
Redis超出最大内存错误OOM command not allowed when used memory &gt; 'maxmemory'
Compilation errors and printout garbled problems caused by Chinese content in vs2019 code
微信小程序利用百度api达成植物识别
Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting
Jinshanyun - 2023 Summer Internship
Verilog 和VHDL有符号数和无符号数相关运算
Wechat applet uses Baidu API to achieve plant recognition
ctf 记录
Verilog and VHDL signed and unsigned number correlation operations
随机推荐
PLC-Recorder快速监控多个PLC位的技巧
mysql 基本语句
ImportError: cannot import name ‘Digraph‘ from ‘graphviz‘
C file and folder operation
Some things configured from ros1 to ros2
map集合赋值到数据库
高德根据轨迹画线
Verilog and VHDL signed and unsigned number correlation operations
TIPC introduction 1
Is bond fund safe? Does the bond buying foundation lose principal?
Principe du contrat évolutif - delegatecall
ASTParser 解析含有emum 枚举方法的类文件的踩坑记
微信小程序利用百度api达成植物识别
抖音海外版TikTok:正与拜登政府敲定最终数据安全协议
MySQL basic statement
由粒子加速器产生的反中子形成的白洞
ros缺少xacro的包
SQLite modify column type
enumrate的start属性的坑
Skills of PLC recorder in quickly monitoring multiple PLC bits