-
在springboot设置Configuration类,配置线程池参数,同时设置@EnableAsync注解
@EnableAsync
@SpringBootConfiguration
public class ThreadPoolConfig {@Value("${threadpool.corePoolSize}") private int corePoolSize; @Value("${threadpool.maxPoolSize}") private int maxPoolSize; @Value("${threadpool.queueCapacity}") private int queueCapacity; @Value("${threadpool.keepAliveSeconds}") private int keepAliveSeconds; @Bean public ThreadPoolTaskExecutor threadPoolTaskExecutor(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setKeepAliveSeconds(keepAliveSeconds); executor.setThreadNamePrefix("ThreadPoolTaskExecutor-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; }
}
2. 配置执行任务类,
# 因为我们使用的是返回异步结果,所以要继承Callable类
public class abcTask implements Callable<ReturnValue> {
#异步任务中无法使用自动注入,所以需要用构造函数传入参数
public abc(){}
#写入任务逻辑
@override
public ReturnValue call() throw Exception {
}
-
在main中调用多线程任务
#创建一个list用于接收多线程执行结果
List<Future<abc>> futures = new ArrayList<>();
for (abc1 abc1 : acbs) {
FutureTask futureTask = new FutureTask<abc>(new abcTask());
#如果需要返回结果的话,这里就使用submit,如果不需要返回结果的话就使用
threadPoolTaskExecutor.submit(futureTask);
futures.add(futureTask);
}#使用for方法从futures list中获取多线程的返回结果