Java多线程批量拆分List导入数据库
目的:加快速度多线程分批导入Mysql依然使用mybatis的批量导入,不同的是,根据线程数目进行分组,然后再建立多线程池,进行导入。代码:public int addFreshStudentsNew(List<A> list) {if (list == null || list.isEmpty()) {return 0;}//你的逻辑操作{...}//开启线程数int n
·
目的:加快速度
多线程分批导入Mysql
依然使用mybatis的批量导入,不同的是,根据线程数目进行分组,然后再建立多线程池,进行导入。
代码:
public int addFreshStudentsNew(List<A> list) {
if (list == null || list.isEmpty()) {
return 0;
}
//你的逻辑操作{...}
//开启线程数
int nThreads = 50;
int size = enrollStudentEntityList.size();
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
List<Future<Integer>> futures = new ArrayList<Future<Integer>>(nThreads);
for (int i = 0; i < nThreads; i++) {
final List<A> listOne = enrollStudentEntityList.subList(size / nThreads * i, size / nThreads * (i + 1));
Callable<Integer> task1 = () -> {
studentSave.saveStudent(listOne);//可多个list
return 1;
};
futures.add(executorService.submit(task1));
}
executorService.shutdown();
if (!futures.isEmpty() && futures != null) {
return 10;
}
return -10;
}
代码说明:
上面是通过应用ExecutorService 建立了固定的线程数,然后根据线程数目进行分组,批量依次导入。一方面可以缓解数据库的压力,另一个面线程数目多了,一定程度会提高程序运行的时间。缺点就是要看服务器的配置,如果配置好的话就可以开多点线程,配置差的话就开小点。建议10个差不多;
更多推荐
已为社区贡献1条内容
所有评论(0)