1.分割
public class SplitListUtils {
/**
* 拆分集合
*
* @param <T> 泛型对象
* @param splitList 需要拆分的集合
* @param subListLength 每个子集合的元素个数
* @return 返回拆分后的各个集合组成的列表
**/
public static <T> List<List<T>> split(List<T> splitList, int subListLength) {
if (CollectionUtils.isEmpty(splitList) || subListLength <= 0) {
return Lists.newArrayList();
}
List<List<T>> ret = Lists.newArrayList();
int size = splitList.size();
if (size <= subListLength) {
//数据量不足subListLength时,直接返回splitList
ret.add(splitList);
} else {
//子集合拥有完整subListLength个元素
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(splitList.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(splitList.get(pre * subListLength + i));
}
ret.add(itemList);
}
}
return ret;
}
public static void main(String[] args) {
List<String> list = Lists.newArrayList();
int size = 1099;
for (int i = 0; i < size; i++) {
list.add("hello-" + i);
}
//大集合里面包含多个小集合
List<List<String>> temps = split(list, 100);
int j = 0;
//对大集合里面的每一个小集合进行操作
for (List<String> obj : temps) {
System.out.println(String.format("row:%s -> size:%s,data:%s", ++j, obj.size(), obj));
}
}
}
2.处理
public class BatchHandleTest {
public void threadMethodWithoutReturn(List<Integer> splitList) {
//初始化线程池, 参数一定要一定要一定要调好!!!!
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(20, 50, 4, TimeUnit.SECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.AbortPolicy());
//大集合拆分成N个小集合, 这里集合的size可以稍微小一些, 以保证多线程异步执行, 过大容易回到单线程模式
List<List<Integer>> splitNList = SplitListUtils.split(splitList, 100);
//记录单个任务的执行次数
CountDownLatch countDownLatch = new CountDownLatch(splitNList.size());
//对拆分的集合进行批量处理, 先拆分的集合, 再多线程执行
for (List<Integer> singleList : splitNList) {
//1.线程池执行(无返回值)
threadPool.execute(new Thread(new Runnable() {
@Override
public void run() {
//业务处理
}
}));
//任务个数-1, 直至为0时唤醒await()
countDownLatch.countDown();
}
}
public void threadMethod(List<Integer> splitList) {
//初始化线程池, 参数一定要一定要一定要调好!!!!
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(20, 50, 4, TimeUnit.SECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.AbortPolicy());
//大集合拆分成N个小集合, 这里集合的size可以稍微小一些, 以保证多线程异步执行, 过大容易回到单线程模式
List<List<Integer>> splitNList = SplitListUtils.split(splitList, 100);
//记录单个任务的执行次数
CountDownLatch countDownLatch = new CountDownLatch(splitNList.size());
//对拆分的集合进行批量处理, 先拆分的集合, 再多线程执行
for (List<Integer> singleList : splitNList) {
//2.线程池执行(有返回值)
threadPool.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
//业务处理
return null;
}
});
//任务个数-1, 直至为0时唤醒await()
countDownLatch.countDown();
}
}
}