import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* @ClassName ThreadUtils
* @Description
* @Author qian
* @Date 2019-07-10 16:31
* @Version 1.0
**/
public class ThreadUtils {
public static List<Object> dataMulThreadDispose(List<ClassEntity> classEntity , String hour){
long startime =System.currentTimeMillis();
int threaSize = 10000;
int dataSize = classEntity.size();
int threaNum = dataSize / threaSize + 1;
boolean special = dataSize % threaSize ==0;
//最后一个结果集:
int lastDateSet =dataSize % threaSize;
//添加参数 new ThreadPoolExecutor().
//ExecutorService exec = Executors.newFixedThreadPool(5);
ExecutorService exec =new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors()+1, Runtime.getRuntime().availableProcessors()+1, 30L, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(16),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
List<Callable<List<Object>>> tasks = new ArrayList<>();
Callable<List<Object>> task = null;
List<ClassEntity> cutList = null;
List<Object> resultMap = new ArrayList<>();
for(int i =0; i<threaNum ; i++){
if( i == threaNum - 1){
if(special){
break;
}
cutList= classEntity.subList(threaSize * i, (threaSize * i)+lastDateSet);
}else {
cutList = classEntity.subList(threaSize * i ,threaSize * (i+1));
}
final List<ClassEntity> dataSets = cutList;
final String condtionHour=hour;
task =new Callable<List<Object>>() {
@Override
public List<Object> call() throws Exception {
List<Object> list=new ArrayList<>();
for(ClassEntity eUserExperienceDataScoreVo : dataSets){
//System.out.println(nowDay+"nowDay"+"datatime"+eUserExperienceDataScoreVo.getDateTime());
if(eUserExperienceDataScoreVo.getDateTime().contains(condtionHour)){
Object[] objects = new Object[3];
objects[0] = eUserExperienceDataScoreVo.getLat();
objects[1] = eUserExperienceDataScoreVo.getLng();
objects[2] = eUserExperienceDataScoreVo.getTotScore();
list.add(objects);
//list.remove(eUserExperienceDataScoreVo);//删除已经添加元素
}
}
return list;
}
};
tasks.add(task);
}
try {
List<Future<List<Object>>> results = exec.invokeAll(tasks);
for (Future<List<Object>> result: results) {
//System.out.println(result.get());
resultMap.addAll(result.get());
}
} catch (Exception e) {
e.printStackTrace();
}
exec.shutdown();
System.out.println("线程任务执行结束");
System.err.println("执行任务消耗了 :" + (System.currentTimeMillis() - startime) + "毫秒");
return resultMap;
}
}
https://www.cnblogs.com/shihaiming/p/8553972.html