/**
 * 线程池配置类
 */
@Configuration
public class ThreadPoolExecutorConfig {
    ThreadFactory threadFactory = new ThreadFactory() {
        private int count = 1; //主要是为了给每个线程取一个名字

        @Override
        public Thread newThread(@NotNull Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("线程 :" + count);
            count++;
            return thread;
        }
    };

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        return new ThreadPoolExecutor(
                2,
                4,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                threadFactory
        );
    }
  • corePoolSize 核心线程数

  • maximumPoolSize 最大线程数

  • keepAliveTime 临时线程存活时间(最大线程数-核心线程数)

  • unit 时间单位

  • workQueue 工作队列

  • threadFactory 线程创建工厂

  • rejectedExecutionHandler 拒绝策略

当任务提交时,优先交给核心线程处理,当核心线程处理不过来时,放入阻塞队列中,当阻塞队列满后,创建临时线程处理后来的任务,当临时线程满后触发拒绝策略,如果不设置拒绝策略则直接抛出异常

//添加任务
CompletableFuture.runAsync(() -> {
    try {
        Thread.sleep(60000);
    } catch (InterruptedException e) {
        throw new BusinessException(ErrorCode.SYSTEM_ERROR, "任务异常");
    }
}, threadPoolExecutor);