https://www.cnblogs.com/yw0219/p/8810956.html
https://www.cnblogs.com/panxuejun/p/9240504.html
在new线程池对象时,发现两个不同的类:
ThreadPoolTaskExecutor //spring封装ThreadPoolExecutor后得到的
ThreadPoolExecutor //由java.util.concurrent...提供的
懵逼了.
啥意思... , 我该用谁... ?
查查看吧. 发现ThreadPoolTaskExecutor是由spring封装了ThreadPoolExecutor,得到的. 所以如果使用spring的话,
那么使用ThreadPoolTaskExecutor就可以了.
创建一个线程池配置类
package com.thread.pool.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; /** * spring线程池配置类 * 使用该类的方法: 在异步执行的方法上添加@Async("taskExecutor") * taskExecutor: 就是当前类中@Bean的方法,也就是通过spring创建的对象 */ @Configuration @EnableAsync public class DemoExecutor { /** * 设置ThreadPoolExecutor的核心池大小. 线程池维护线程的最少数量 */ private int corePoolSize = 10; /** * 设置ThreadPoolExecutor的最大池大小. */ private int maxPoolSize = 200; /** * 设置ThreadPoolExecutor的阻塞队列的容量,即最大等待任务数 线程池所使用的缓冲队列 */ private int queueCapacity = 10; /** * 配置线程池中的线程的名称前缀 */ private String threadNamePrefix = "async-service-"; /** * 设置线程活跃时间(秒)维护线程所允许的空闲时间 */ //private int keepAliveSeconds = 60; @Bean public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix(threadNamePrefix); //executor.setKeepAliveSeconds(keepAliveSeconds); /** 等待所有线程执行完, 在关机.如果没有优雅停机,存在于线程池中的任务将会被强制停止,导致部分任务失败 */ executor.setWaitForTasksToCompleteOnShutdown(true); /** * 当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize, * 如果还有任务到来就会采取任务拒绝策略,通常有以下四种策略: * ThreadPoolExecutor.AbortPolicy: 丢弃任务并抛出RejectedExecutionException异常。 * ThreadPoolExecutor.DiscardPolicy: 也是丢弃任务,但是不抛出异常。 * ThreadPoolExecutor.DiscardOldestPolicy: 丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程) * ThreadPoolExecutor.CallerRunsPolicy: 由调用线程处理该任务 */ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
