工具
public <T> void accelerateThread(Consumer<List<T>> consumer,List<T> targetList,Integer threadSize) throws InstantiationException, IllegalAccessException, InterruptedException, ExecutionException {
if (targetList == null || targetList.size() == 0) {
return;
}
if (threadSize == null) {
throw new RuntimeException("线程大小(threadSize)不能为空!");
}
if (threadSize > 100) {
throw new RuntimeException("线程大小不能超过100!");
}
List<Future<?>> resultList = new ArrayList<Future<?>>();
int listSize = targetList.size();
Integer divideSize = targetList.size() / threadSize;
if(divideSize.intValue() == 0) {
divideSize = targetList.size();
threadSize = 1;
}
CompletableFuture<Void> completableFuture = null;
for (int i = 0; i < threadSize; i++) {
List<T> list = (i == threadSize-1) ? targetList.subList(i* divideSize, listSize)
: targetList.subList(i* divideSize, (i + 1) * divideSize);
completableFuture = CompletableFuture.runAsync(()->consumer.accept(list),threadPoolTaskExecutor);
resultList.add(completableFuture);
}
CompletableFuture.allOf(resultList.stream().toArray(CompletableFuture[]::new)).join();
}
public static TaskExecutor getInstance() {
if (taskExecutor == null) {
taskExecutor = new TaskExecutor();
}
return taskExecutor;
}
具体业务实现举例
/**
* 制作多线程
* 传来 models 用户集合;制作多线程分别对用户同时进行相同的操作,提高速度
* @return
* @throws BusinessException
*/
public List<Model> getThreadList(List<Model> models) throws BusinessException {
List<Model> threadList = Collections.synchronizedList(new ArrayList<>());
Consumer<List<Model>> consumer = temps -> {
//写业务操作
for (Model model : temps) {
Boolean flag = poService.isGoodModel(model.getNick()); //用户是好用户
if (flag) {
threadList.add(model);
}
}
};
try {
TaskExecutor.getInstance().accelerateThread(consumer, models, 100);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return threadList;
}
有问题可以留言探讨一下。