当前位置:网站首页>多线程浅谈
多线程浅谈
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进阶资料,面试资料,关注公众号
边栏推荐
- MySQL high performance optimization notes (including 578 pages of notes PDF document), collected
- 【MySQL】sql给表起别名
- 试着换个角度理解低代码平台设计的本质
- leetcode/乘积小于K 的连续子数组的个数
- Force deduction brush question (1): sum of two numbers
- Mathematical modeling -- Optimization of picking in warehouse
- “蔚来杯“2022牛客暑期多校训练营2,签到题GJK
- [MySQL] SQL aliases the table
- 【ONE·Data || 数组堆简单实现及其延伸】
- MySQL stores JSON format data
猜你喜欢

iVX低代码平台系列详解 -- 概述篇(二)

What is the function of data parsing?

In 2022, the official data of programming language ranking came, which was an eye opener

Realization of digital tube display based on C51
![[UE4] replay game playback for ue4.26](/img/c3/1c7b30797f46dbd323cac4d158600f.png)
[UE4] replay game playback for ue4.26

C语言提高篇(一)

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

Internet of things development -- mqtt message server emqx

The problem of modifying the coordinate system of point cloud image loaded by ndtmatching function in autoware

Type analysis of demultiplexer (demultiplexer)
随机推荐
Flexible layout single selection
In 2022, the official data of programming language ranking came, which was an eye opener
「活动推荐」冲冲冲!2022 国际开源节有新内容
Internet of things development -- mqtt message server emqx
Navigation--实现Fragment之间数据传递和数据共享
Navigation -- realize data transmission and data sharing between fragments
QT memory management tips
Understand the working principle of timer in STM32 in simple terms
Click back to the top JS
Motionlayout -- realize animation in visual editor
字符流综合练习解题过程
Mathematical modeling -- red wine quality classification
Related function records about string processing (long-term update)
第十四天:续第十三天标签相关知识
TI C6000 TMS320C6678 DSP+ Zynq-7045的PS + PL异构多核案例开发手册(2)
费曼学习法(符号表)
2022年编程语言排名,官方数据来了,让人大开眼界
[circuit design] peak voltage and surge current
Opencv image sharpness evaluation (camera autofocus)
Excel 打开包含汉字的 csv 文件出现乱码该怎么办?