当前位置:网站首页>多线程浅谈
多线程浅谈
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之数据查询(多表查询)
- 12. < tag dynamic programming and subsequence, subarray> lt.72. edit distance
- Leetcode/ and continuous shortest subarray greater than or equal to target
- Mysql存储json格式数据
- (CVPR-2019)选择性的内核网络
- The growth path of embedded engineers
- 数学建模——带相变材料的低温防护服御寒仿真模拟
- Read the recent trends of okaleido tiger and tap the value and potential behind it
- Leetcode/0 and 1 consecutive subarrays with the same number
- 点击按钮,下滑到指定的位置
猜你喜欢

Mobile communication -- simulation model of error control system based on convolutional code
![[circuit design] open collector OC output of triode](/img/48/5a111b81f0d99990fbcc5263313c07.jpg)
[circuit design] open collector OC output of triode

Cookies and sessions

What is browser fingerprint recognition

数学建模——带相变材料的低温防护服御寒仿真模拟

What is scope and scope chain

Type analysis of demultiplexer (demultiplexer)
![[circuit design] convert AC AC to DC](/img/b4/67df7f4555379c63694e89055499bb.jpg)
[circuit design] convert AC AC to DC

Comprehensive use method of C treeview control

实验二:Arduino的三色灯实验
随机推荐
Cookies and sessions
Leetcode/0 and 1 consecutive subarrays with the same number
Mathematical modeling -- cold proof simulation of low temperature protective clothing with phase change materials
Mathematical modeling -- bus scheduling optimization
Mathematical modeling -- red wine quality classification
MySQL之数据查询(多表查询)
Promise solves asynchrony
Control buzzer based on C51
Jetpack--了解ViewModel和LiveData的使用
Understand the working principle of timer in STM32 in simple terms
Blind separation of speech signals based on ICA and DL
What is browser fingerprint recognition
What is scope and scope chain
Mathematical modeling -- the laying of water pipes
Why can't Bi software do correlation analysis
什么是作用域和作用域链
Lm13 morphological quantification momentum period analysis
Sharpness evaluation method without reference image
年中总结 | 与自己对话,活在当下,每走一步都算数
基于C51实现数码管的显示