| 10 | |
| 11 | //线程池 |
| 12 | @Configuration |
| 13 | @EnableAsync |
| 14 | public class PoolConfig { |
| 15 | ThreadPoolProperties properties = new ThreadPoolProperties(); |
| 16 | @Bean(name = "taskExecutor") |
| 17 | public ThreadPoolTaskExecutor taskExecutor() { |
| 18 | ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); |
| 19 | executor.setCorePoolSize(properties.getCorePoolSize()); //设置核心线程数 |
| 20 | executor.setMaxPoolSize(properties.getMaxPoolSize()); //设置最大线程数 |
| 21 | executor.setQueueCapacity(properties.getQueueCapacity()); //设置队列容量 |
| 22 | executor.setThreadNamePrefix(properties.getThreadNamePrefix()); |
| 23 | executor.setKeepAliveSeconds(properties.getKeepAliveTime()); |
| 24 | executor.setWaitForTasksToCompleteOnShutdown(properties.isWaitForTasksToCompleteOnShutdown()); |
| 25 | executor.setAwaitTerminationSeconds(properties.getAwaitTerminationSeconds()); |
| 26 | // 设置任务拒绝策略 |
| 27 | /** |
| 28 | * 4种 |
| 29 | * ThreadPoolExecutor类有几个内部实现类来处理这类情况: |
| 30 | - AbortPolicy 丢弃任务,抛RejectedExecutionException |
| 31 | - CallerRunsPolicy 由该线程调用线程运行。直接调用Runnable的run方法运行。 |
| 32 | - DiscardPolicy 抛弃策略,直接丢弃这个新提交的任务 |
| 33 | - DiscardOldestPolicy 抛弃旧任务策略,从队列中踢出最先进入队列(最后一个执行)的任务 |
| 34 | * 实现RejectedExecutionHandler接口,可自定义处理器 |
| 35 | */ |
| 36 | executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); |
| 37 | return executor; |
| 38 | } |
| 39 | |
| 40 | @Data |
| 41 | class ThreadPoolProperties { |
| 42 | private int corePoolSize = 5; |
| 43 | private int maxPoolSize = 50; |
| 44 | private int keepAliveTime = 15; |
| 45 | private int queueCapacity = 10; |
| 46 | private String threadNamePrefix = "Tbed-Thread"; |
| 47 | private boolean allowCoreThreadTimeout = false; |
| 48 | private boolean waitForTasksToCompleteOnShutdown = false; |
| 49 | private int awaitTerminationSeconds; |
| 50 | |
| 51 | } |
| 52 | } |
nothing calls this directly
no outgoing calls
no test coverage detected