数据分割
public class MyThread {
/**
*
* @param resList 导入的集合
* @param subListLength 分割的大小
* @param <T>
* @return
*/
public <T> List<List<T>> split(List<T> resList, int subListLength) {
if (CollectionUtils.isEmpty(resList) || subListLength <= 0) {
return Lists.newArrayList();
}
List<List<T>> ret = Lists.newArrayList();
int size = resList.size();
if (size <= subListLength) {
// 数据量不足 subListLength 指定的大小
ret.add(resList);
} else {
int pre = size / subListLength;
int last = size % subListLength;
// 前面pre个集合,每个大小都是 subListLength 个元素
for (int i = 0; i < pre; i++) {
List<T> itemList = Lists.newArrayList();
for (int j = 0; j < subListLength; j++) {
itemList.add(resList.get(i * subListLength + j));
}
ret.add(itemList);
}
// last的进行处理
if (last > 0) {
List<T> itemList = Lists.newArrayList();
for (int i = 0; i < last; i++) {
itemList.add(resList.get(pre * subListLength + i));
}
ret.add(itemList);
}
}
return ret;
}
}
多线程导入
@Test
void f() {
List<Wo> list = woService.list();
MyThread myThread = new MyThread();
List<List<Wo>> split = myThread.split(list, 100);
int n = split.size();
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(20, 50,
4, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new ThreadPoolExecutor.AbortPolicy());
CountDownLatch countDownLatch = new CountDownLatch(n);
for (List<Wo> wos : split) {
threadPool.execute(() -> {
List<Eo> eos = wos.stream().map(wo -> {
Eo eo = new Eo();
BeanUtils.copyProperties(wo, eo);
return eo;
}).collect(Collectors.toList());
eoService.saveBatch(eos);
countDownLatch.countDown();
});
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}