多线程处理List返回操作结果
package gms.Panorama.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
/**
* 多线程处理list集合
*
*/
public class ThreadsTestAA {
/**
* 使用多线程处理数据
* @param list
* @param nThreads
* @throws Exception
*/
public static void processList2(List<Object> list,final int nThreads) throws Exception {
// 存最后的结果
StringBuffer ret = new StringBuffer();
if (list == null || list.isEmpty()) {
//这里可以根据自己的业务需要去做处理
System.out.println("要处理的数据为空");
}
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
List<Future<Object>> futures = new ArrayList<Future<Object>>(nThreads);
/**集合总条数**/
int size = list.size();
/**将集合切分的段数**/
int listStart,listEnd;
//根据线程 进行数据的拆分
for (int i = 0; i < nThreads; i++) {
/***计算切割 开始和结束**/
listStart = size / nThreads * i ;
listEnd = size / nThreads * ( i + 1 );
/**最后一段线程会 出现与其他线程不等的情况**/
if(i == nThreads - 1){
listEnd = size;
}
final List<Object> subList = list.subList(listStart, listEnd);
Callable<Object> task = new Callable<Object>() {
@Override
public Object call() throws Exception {
//存当前线程处理的数据,最后统一汇总打印
StringBuffer sb = new StringBuffer();
for (Object str : subList) {
sb.append(str+"\t");
}
return sb.toString();
}
};
futures.add(executorService.submit(task));
}
// 汇总处理的结果
for (Future<Object> future : futures) {
ret.append(future.get());
}
executorService.shutdown();
System.out.println("并发处理结果: "+ret.toString());
}
public static void main(String[] args) throws Exception{
List<Object> list = new ArrayList<>();
for(int i=0;i<4;i++){
list.add(String.valueOf(i));
}
processList2(list,5);
}
}