SpringBoot中的线程池ThreadPoolTaskExecutor,@Async的使用
线程池
@Configuration
@EnableAsync
public class ExcutorConfig {
@Bean(name = "ThreadPoolTaskExecutor")
public ThreadPoolTaskExecutor ThreadPoolTaskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数量,线程池创建时候初始化的线程数
executor.setCorePoolSize(5);
//最大线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(15);
//缓冲队列,用来缓冲执行任务的队列
executor.setQueueCapacity(20);
//当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(600);
//设置好了之后可以方便我们定位处理任务所在的线程池
executor.setThreadNamePrefix("MyThreadPool");
//用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
executor.setWaitForTasksToCompleteOnShutdown(true);
//该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。
executor.setAwaitTerminationSeconds(60);
//线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
// 通过spring @Bean方式注入ThreadPoolTaskExecutor实例时,可以不需要这一步。
// 由于ThreadPoolTaskExecutor继承了ExecutorConfigurationSupport,初始化对象时会调用ExecutorConfigurationSupport.afterPropertiesSet()
executor.initialize();
return executor;
}
}
异步方法,指定使用线程池 :ThreadPoolTaskExecutor
@Async("ThreadPoolTaskExecutor")
public void writeFile(List<String> list, CountDownLatch count){
try (BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(Paths.get("output.txt")))) {
bos.write(String.join("", list).getBytes());
log.info("{}{}", "---"+System.currentTimeMillis()+"--- ", "ThreadName: "+Thread.currentThread().getName());
} catch (IOException e) {
e.printStackTrace();
}
finally {
count.countDown();
}
}
调用异步方法
public void testThreadWrite(){
ArrayList<ArrayList<String>> lists = new ArrayList<>();
for (int i = 0; i < 100; i++) {
ArrayList<String> list = new ArrayList<>();
for (int j = 0; j < 100000; j++) {
list.add("jinnanDu:"+"_"+j+"_"+i);
}
lists.add(list);
}
CountDownLatch count = new CountDownLatch(lists.size());
for(ArrayList<String> list : lists){
asyncService.writeFile(list,count);
}
//所有任务执行完成后,日志打印结果
try {
count.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info("all jobs finished");
}
执行结果