Java中List集合使⽤多线程分段处理因业务需要,需从excel读取数据并插⼊数据库,由于数据量较⼤,耗时较长,考虑使⽤多线程来处理
1.读取到的list按数据量分段
2.动态创建线程
public class ScmcommissionLineServiceImpl{
//导⼊数据
public void importData(List list){
//500分⼀组
int count = 500;
int listSize = list.size();
//线程数
int RunSize = (listSize / count)+1;
ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(RunSize);
CountDownLatch countDownLatch = new CountDownLatch(RunSize);
for (int i = 0; i < RunSize; i++) {
List newList = null ;
if((i+1)==RunSize){
int startIndex = (i*count);;
int endIndex = list.size();
newList =list.subList(startIndex,endIndex);
}else{
java中index是什么意思int startIndex = i*count;;
int endIndex = (i+1)*count-1;
newList =list.subList(startIndex,endIndex);
}
ImportTask task= new ImportTask (newList,countDownLatch);
}
countDownLatch.await(); //主线程等待所有线程完成任务
//所有线程完成任务后的⼀些业务
System.out.println("插⼊数据完成!");
.....
//关闭线程池
executor.shutdown();
}
}
class ImportTask implements Runnable{
private List list;
private CountDownLatch countDownLatch;
public ImportTask (List list,CountDownLatch countDownLatch){
this.list = list ;
}
@Override
public void run() {
if(null!=list){
//业务逻辑
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论