CompleteFuture自定义线程池
object ThreadPoolConstant {
const val CORE_POOL_SIZE = 4
const val MAX_POOL_SIZE = 30
const val QUEUE_CAPACITY = 100
const val THREAD_NAME_PREFIX = "my-Executor-"
}
config
@Configuration
class ThreadPool {
@Bean("asyncExecutor")
fun asyncExecutor(): Executor {
val threadPoolTaskExecutor = ThreadPoolTaskExecutor()
// 配置核心线程数
threadPoolTaskExecutor.corePoolSize = ThreadPoolConstant.CORE_POOL_SIZE
// 最大线程数
threadPoolTaskExecutor.maxPoolSize = ThreadPoolConstant.MAX_POOL_SIZE
// 队列大小
threadPoolTaskExecutor.setQueueCapacity(ThreadPoolConstant.QUEUE_CAPACITY)
// 名称前缀
threadPoolTaskExecutor.setThreadNamePrefix(ThreadPoolConstant.THREAD_NAME_PREFIX)
// rejection-policy: 当pool已经达到max size时,如何处理新任务:
// CallerRunsPolicy: 不在新线程中执行任务,而是由调用者所在的线程来执行;
// AbortPolicy: 拒绝执行新任务,并抛出RejectedExecutionException异常;
// DiscardPolicy:丢弃当前将要加入队列的任务;
// DiscardOldestPolicy:丢弃任务队列中最旧的任务;
threadPoolTaskExecutor.setRejectedExecutionHandler(ThreadPoolExecutor.CallerRunsPolicy())
threadPoolTaskExecutor.initialize()
return threadPoolTaskExecutor
}
}