当前位置:网站首页>多线程浅谈
多线程浅谈
2022-07-29 01:37:00 【xy29981】
1 循环调用
这种情况,一般都循环调用同一段代码,每次循环的逻辑一致,前后不关联。比如说,我们要初始化一个列表,预置12个月的数据给前端:
List<Model> list = new ArrayList<>();
for(int i = 0 ; i < 12 ; i ++) {
Model model = calOneMonthData(i); // 计算某个月的数据,逻辑比较复杂,难以批量计算,效率也无法很高
list.add(model);
}
这种显然每个月的数据计算相互都是独立的,我们完全可以采用多线程方式进行:
// 建立一个线程池,注意要放在外面,不要每次执行代码就建立一个,具体线程池的使用就不展开了
public static ExecutorService commonThreadPool = new ThreadPoolExecutor(5, 5, 300L,
TimeUnit.SECONDS, new LinkedBlockingQueue<>(10), commonThreadFactory, new ThreadPoolExecutor.DiscardPolicy());
// 开始多线程调用
List<Future<Model>> futures = new ArrayList<>();
for(int i = 0 ; i < 12 ; i ++) {
Future<Model> future = commonThreadPool.submit(() -> calOneMonthData(i););
futures.add(future);
}
// 获取结果
List<Model> list = new ArrayList<>();
try {
for (int i = 0 ; i < futures.size() ; i ++) {
list.add(futures.get(i).get());
}
} catch (Exception e) {
LOGGER.error("出现错误:", e);
}
2.2 顺序调用
如果不是类似上面循环调用,而是一次次的顺序调用,而且调用之间没有结果上的依赖,那么也可以用多线程的方式进行,例如:

代码上看:
A a = doA();
B b = doB();
C c = doC(a, b);
D d = doD(c);
E e = doE(c);
return doResult(d, e);
那么可用CompletableFuture解决
CompletableFuture<A> futureA = CompletableFuture.supplyAsync(() -> doA());
CompletableFuture<B> futureB = CompletableFuture.supplyAsync(() -> doB());
CompletableFuture.allOf(futureA,futureB) // 等a b 两个任务都执行完成
C c = doC(futureA.join(), futureB.join());
CompletableFuture<D> futureD = CompletableFuture.supplyAsync(() -> doD(c));
CompletableFuture<E> futureE = CompletableFuture.supplyAsync(() -> doE(c));
CompletableFuture.allOf(futureD,futureE) // 等d e两个任务都执行完成
return doResult(futureD.join(),futureE.join());
这样A B 两个逻辑可以并行执行,D E两个逻辑可以并行执行,最大执行时间取决于哪个逻辑更慢。
敬请期待我的下一篇文章,谢谢。

更多java进阶资料,面试资料,关注公众号
边栏推荐
- Why can't Bi software do correlation analysis
- Anti crawler mechanism solution: JS code generates random strings locally
- Have you ever encountered the situation that the IP is blocked when crawling web pages?
- JVM内存溢出在线分析Dump文件以及在线分析打开.hprof文件得出JVM运行报告jvisualvm怎么在线分析
- leetcode/乘积小于K 的连续子数组的个数
- Qt 内存管理小技巧
- druid. The performance of IO + tranquility real-time tasks is summarized with the help of 2020 double 11
- [electronic components] constant voltage, amplify the current of the load (triode knowledge summary)
- 第十五天(VLAN相关知识)
- druid. io index_ Realtime real-time query
猜你喜欢

字符流综合练习解题过程

LeetCode 练习——剑指 Offer 45. 把数组排成最小的数
![[simple implementation and extension of one · data | array heap]](/img/47/6f2c0d5c85cf05a24ba7adbd61e014.png)
[simple implementation and extension of one · data | array heap]

MotionLayout--在可视化编辑器中实现动画

LM13丨形态量化-动量周期分析

Internet of things development -- mqtt message server emqx

Implementation of 10m multifunctional signal generator with FPGA

Mathematical modeling -- the laying of water pipes

JetPack--Navigation实现页面跳转

Realization of digital tube display based on C51
随机推荐
防止重复点击
Qt 内存管理小技巧
[electronic components] constant voltage, amplify the current of the load (triode knowledge summary)
Navigation -- realize data transmission and data sharing between fragments
Mathematical modeling -- red wine quality classification
H5 background music is played automatically by touch
Motionlayout -- realize animation in visual editor
Leetcode exercise - Sword finger offer 45. arrange the array into the smallest number
点击按钮,下滑到指定的位置
Ignore wechat font settings
Ciscn 2022 central China Misc
How to find the right agent type? Multi angle analysis for you!
(cvpr-2019) selective kernel network
leetcode/0和1个数相同的连续子数组
LeetCode 练习——剑指 Offer 45. 把数组排成最小的数
[cloud native] what is the microservice architecture
E-commerce keyword research helps data collection
Try to understand the essence of low code platform design from another angle
Navigation--实现Fragment之间数据传递和数据共享
Blind separation of speech signals based on ICA and DL