记录一次多线程处理list集合的过程
方法:
//计数
static AtomicInteger count = new AtomicInteger(0);
//处理方法
public String moFee(List<JSONObject> list, final int nThreads)
throws Exception {
if (list == null || list.isEmpty()) {
return null;
}
StringBuffer ret = new StringBuffer();
int size = list.size();
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
List<Future<String>> futures = new ArrayList<Future<String>>(nThreads);
for (int i = 0; i < nThreads; i++) {
final List<JSONObject> subList = list.subList(size / nThreads * i, size / nThreads * (i + 1));
Callable<String> task = new Callable<String>() {
@Override
public String call() throws Exception {
String currentMonth = DateUtil.getYearMonth(new Date());
for (JSONObject jsonObject : subList) {
// 处理逻辑
//todo
count.getAndIncrement();
System.out.println(count.get());
System.out.println("===========================>");
}
return "";
}
};
futures.add(executorService.submit(task));
}
executorService.shutdown();
while (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
System.out.println("线程池没有关闭");
}
return ret.toString();
}