package com.qiwu.inference.common.config; import jodd.util.concurrent.ThreadFactoryBuilder; import org.jetbrains.annotations.NotNull; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import java.util.concurrent.*; @Configuration @EnableAsync public class ThreadPoolConfig { @Bean(value = "threadPoolInstance") public Executor myThreadPool() { //核心线程数 int corePoolSize = 5; //最大线程数 int maxPoolSize = 7; //设置工作队列大小 int queueCapacity = 1000; //最大存活时间 long keepAliveTime = 30; //设置线程名称前缀 String threadNamePrefix = "threadPool-->"; //设置自定义拒绝策略 RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) { throw new RuntimeException("线程数已超过最大线程数"); } }; //自定义线程工厂 ThreadFactory threadFactory = new ThreadFactory() { private int i = 1; @Override public Thread newThread(@NotNull Runnable runnable) { Thread thread = new Thread(runnable); thread.setName(threadNamePrefix + i); i++; return thread; } }; //初始化线程 return new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueCapacity), threadFactory, rejectedExecutionHandler); } }