ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2,
(int) (Runtime.getRuntime().availableProcessors() / (1 - 0.9)), 200, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(20), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
//线程释放
threadPoolExecutor.setKeepAliveTime(200, TimeUnit.MILLISECONDS);
threadPoolExecutor.allowCoreThreadTimeOut(true);
ExecutorService executor = threadPoolExecutor;
CompletionService<Object> completionService =
new ExecutorCompletionService<>(
executor);
try {
final List<Future<Object>> futures = new ArrayList<>();
int i = 0;
// 多线程启动解析服务
for (AutomateVO automateVO : automateVOList) {
i++;
Future<Object> future = completionService
.submit(new Callable<Object>() {
@Override
public Object call() {
return dosomething...;
}
});
if (future != null) {
futures.add(future);
}
}
int nums = 0;
// 判断执行结果
for (int j = 0; j < futures.size(); j++) {
nums = j;
Object paramE = null;
try {
Future future = completionService.poll();
if (future != null) {
paramE = future.get();
}
} catch (InterruptedException e) {
ExceptionUtils.wrapBusinessException(e.getMessage());
} catch (ExecutionException e) {
ExceptionUtils.wrapBusinessException(e.getMessage());
}
if (paramE != null) {
rstList.add(paramE);
}
}
} finally {
executor.shutdown();
}
注意线程池的策略方式,不同的策略方式决定线程如何执行