zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Java对List分割及使用Spring多线程调用

2023-02-18 16:45:41 时间

一、
功能描述:
1.对List中的数据进行分割并作为参数使用多线程处理对应逻辑
2.避免了使用runnable方式和spring容器中的bean无法注入的问题
3.可以极大提高程序的执行效率、本程序中的线程数可以灵活配置
二、

代码1:

public Object demo() {
//1.获取对应list
List otcOpenAccountLogList = otcOpenAccountLogMapper.list();
if (otcOpenAccountLogList == null || otcOpenAccountLogList.size() == 0) {
return setResultError("获取用户信息失败!");
}
//2.定义线程数量、此处可以根据需要灵活配置到配置文件或数据库表中等
Integer runnableNum = 2;
//3.获取list大小
Integer listSize = otcOpenAccountLogList.size();
//4.校验线程数是否合法
if (runnableNum <= 0 || runnableNum > listSize) {
return setResultError("请设置合适的线程数!");
}
//5.list大小对线程数整除
Integer num = listSize / runnableNum;
//6.list大小对线程数取余
Integer modNum = listSize % runnableNum;
//7.定义每个线程需要处理多少数据量
Integer dataNum = 0;
//8.计算每个线程需要处理多少数据量、如果余数为0则为(list大小对线程数整除) 否则为(list大小对线程数整除+1)
if (modNum == 0) {
dataNum = num;
} else {
dataNum = num + 1;
}
//根据线程数循环遍历开启线程
for (int i = 0; i < runnableNum; i++) {
if (i == 0) {
//当i=0时的list分割及调用线程传参
List otcOpenAccountLogSubList = otcOpenAccountLogList.subList(i, (i + 1) * dataNum);
payApiRunnableService.executeAsyncTask(otcOpenAccountLogSubList, this);
} else {
List otcOpenAccountLogSubList = otcOpenAccountLogList.subList((i) * dataNum, (i + 1) * dataNum);
payApiRunnableService.executeAsyncTask(otcOpenAccountLogSubList, this);
}
}
return setResultSuccess();
}

代码2(线程处理逻辑):

@Async //注解@Async表示该方法为异步任务
public void executeAsyncTask(List otcOpenAccountLogList, PayApiService payApiService) {
logger.info("线程开启.....");
//1.参数校验
if (otcOpenAccountLogList == null || otcOpenAccountLogList.size() == 0) {
return;
}
//2.按自己需求循环遍历子list进行相关处理
for (OtcOpenAccountLog otcOpenAccountLog : otcOpenAccountLogList) {
logger.info("逻辑处理.....");
}
logger.info("线程结束.....");
}

代码3(在springboot启动类开启异步功能):

@EnableAsync //注解@EnableAsync表示启动异步功能
@MapperScan("com.otc.mapper")
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}

三、
声明:本文如有不妥之处,恳请大家指正,有什么不懂得可以私信我。