业务场景
最近工作中遇到一个问题,在做统计工作的时候,由于之前设计的表的数据字段不是很合理,导致现在统计有点耗时。需要循环很多遍来计算,这样调用数据库的时间就是N次数*每次执行时间。显然不满足客户的要求的。
解决办法
在java主线程中 开多个线程来执行任务,主线程等待这些线程都执行完毕,将结果汇总返回给客户端。
具体实现
//普通版start
for (int i = 0; i < list.size(); i++) {
String code = list.get(i).get("deptCode").toString();
String name = list.get(i).get("deptName").toString();
int total = indexMapper.getQuxianTotal(code);
map.put(name,total);
}
//普通版end 经测试 本系统耗时10s
//多线程版start
int size = list.size();
if (size > 0) {
final CountDownLatch latch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
String code = list.get(i).get("deptCode").toString();
String name = list.get(i).get("deptName").toString();
new Thread(
new Runnable() {
@Override
public void run() {
int total = indexMapper.getQuxianTotal(code);
map.put(name, total);
System.out.println("子线程执行");
latch.countDown();
}
}
).start();
}
try {
latch.await();
System.out.println("主线程执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//多线程版 end 经测试 本系统耗时 2.7s
总结
从开发机执行的时间来看,合适的使用多线程,可以加快任务执行速度。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。