引入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework-version}</version>
</dependency>
spring bean
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="10"/>
<property name="keepAliveSeconds" value="200"/>
<property name="maxPoolSize" value="50"/>
</bean>
注入线程池
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
执行
List<T> taskList = Lists.newArrayList(); //任务列表
List<T> resultList = Lists.newArrayList(); //执行结果列表
List<Future<T>> futures = Lists.newArrayList(); //异步计算列表
taskList.forEach(task -> futures.add(taskExecutor.submit(() -> {process task...}))); // ()->: 匿名有返回值的线程Callable
for (int i = 0; i < futures.size(); i++) {
try {
resultList.add(futures.get(i).get(10, TimeUnit.SECONDS)); //超时设置
} catch (Exception e) {
log.error("process error: ", e);
}
}