在项目中经常遇到需要处理大数据量的问题,我们可以把任务拆分通过多线程来缩短处理时间。
初始化线程,通过completionService .submit() 把任务加入线程。
private ExecutorService executorService= Executors.newFixedThreadPool(300);
ExecutorCompletionService<String> completionService = new ExecutorCompletionService<String> (executorService);
for (int k = 1; k <= total/loadNum+1; k++) {
//加入线程,处理结果为String 也可以是自己需要的类型
completionService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
//TODO 处理业务
}
});
}
// 通过completionService.take().get()获取线程处理结果。
for(int i = 1; i <= total/loadNum+1; i++){
try {
String status = completionService.take().get();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}