使用CompletionService可以简便的实现多线程执行任务后获取结果汇总。
//定义线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(5,10,5, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1000));
CompletionService<List<MetaColumn>> completionService = new ExecutorCompletionService<>(executor);
定义执行类
public class ColumnContrastSearch implements Callable<List<MyResult>> {
private Long id;
//还可以将业务service层的对象注入使用
public ColumnContrastSearch() {
}
@Override
public List<MyResult> call() throws Exception {
//业务代码
}
}
将多个执行类放在的集合中,然后执行
List<Future<List<MyResult>>> futureList = new CopyOnWriteArrayList<>();
for (ColumnContrastSearch search : searchList) {
Future<List<MyResult>> future = completionService.submit(search);
futureList.add(future);
}
long start = System.currentTimeMillis();
while (futureList.size() > 0){
for (Future<List<MyResult>> future : futureList) {
if (future.isDone()) {
try {
List<MyResult> object = future.get(5, TimeUnit.MINUTES);
list.addAll(object);
futureList.remove(future);
} catch (Exception e){
logger.error(e.getMessage(),e);
throw ....
}
}
}
//10分钟超时退出
if(System.currentTimeMillis() - start > 1000 * 60 * 10){
logger.info("耗时超过10分钟,超时退出");
break;
}
}