线程池配置
@Configuration
@EnableAsync
public class TaskExecutorConfig {
/**
* 异步处理线程
* @return
*/
@Bean(name = "screenTaskExecutor")
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数:线程池创建时候初始化的线程数
executor.setCorePoolSize(5);
// 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(10);
// 允许线程的空闲时间(秒):当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(600);
// 设置线程名称
executor.setThreadNamePrefix("Screen-");
// 设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
}
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
controller
@Autowired
private Test test;
@RequestMapping("/test1/find3")
public String find23() throws InterruptedException, ExecutionException {
//循环查询9个月的汇总数据
//开始时间
long start = System.currentTimeMillis();
//9个月循环9次
int month = 9;
List<Integer> all = new ArrayList<>();
//阻塞队列 存每个线程获取的 Future 数据
BlockingQueue<Future<List<Integer>>> queue = new LinkedBlockingQueue();
CountDownLatch countDownLatch = new CountDownLatch(month);
Random random = new Random();
for (int i = 1; i <= month; i++) {
System.out.println("月份"+i+"查询开始时间"+System.currentTimeMillis());
//模拟db查询需要时间
Long time = Long.parseLong(String.valueOf((random.nextInt(90)+10)*100));
Future<List<Integer>> list = test.getList(countDownLatch,time);
queue.add(list);
}
countDownLatch.await();
/* 汇总结果 */
for(Future<List<Integer>> future : queue) {
List<Integer> list = future.get();
all.addAll(list);
}
System.out.println("结果="+all);
long cost = System.currentTimeMillis() - start;
String logStr = String.format("查询耗时: %s ms", cost);
System.out.println(logStr);
return logStr;
}
service
@Service
public class Test {
private static Random random = new Random();
@Async("screenTaskExecutor")
public Future<List<Integer>> getList(CountDownLatch countDownLatch,Long sui) throws InterruptedException {
System.out.println("线程"+Thread.currentThread().getName()+"随机sleep时间 "+sui);
List<Integer> list = new ArrayList<>();
//[1,10]内的随机整数
int n3 =random.nextInt(10)+1;
for (int i = 0; i < n3; i++) {
list.add(i);
}
// 1s - 9s 随机睡眠
Thread.sleep(sui);
countDownLatch.countDown();
System.out.println(list);
return new AsyncResult<List<Integer>>(list);
}
}
结果