1.建个线程池
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
private static final int corePoolSize = 50;
private static final int maxPoolSize = 100;
private static final int keepAliveTime = 10;
private static final int queueCapacity = 200;
private static final String threadNamePrefix = "Async-Service-";
@Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
public ThreadPoolTaskExecutor getAsyncExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数(默认线程数)
executor.setCorePoolSize(corePoolSize);
// 最大线程数
executor.setMaxPoolSize(maxPoolSize);
// 缓冲队列数
executor.setQueueCapacity(queueCapacity);
// 允许线程空闲时间(单位:默认为秒)
executor.setKeepAliveSeconds(keepAliveTime);
// 线程池名前缀
executor.setThreadNamePrefix(threadNamePrefix);
// 线程池对拒绝任务的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
}
}
2. 使用
子线程业务代码
// 主线程业务代码
@Override
public List<Map> selectList(PageRequest pageRequest) {
List<Future<List<Map>>> futureList = new ArrayList<>(lines.size());
List<Map> mapList = new ArrayList<>();
futureList.forEach(f -> {
try {
// 主线程等待 获取 子线程 数据
while (true){
if (f.isDone() && !f.isCancelled()) {
break;
}
}
mapList.addAll(f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
return mapList;
}
// 子线程业务代码
@Override
@Async("taskExecutor")
public Future<List<Map>> buildLineMap(){
List<Map> l = new ArrayList<>();
// 业务处理。。。。
l.add(xxx);
return new AsyncResult<>(l);
}