package com.example.demo.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;

@Configuration
@EnableAsync
public class ThreadPoolConfig {


    @Bean(name = "userAccessThreadPool")
    public Executor userAccessThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(6);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量

        executor.setQueueCapacity(20);
//        executor.setQueueCapacity(10);
//        在提交任务是10个之前都是单线程执行，到第11个时就会开辟新线程执行第11个任务
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        // 设置线程名称前缀
        executor.setThreadNamePrefix("user-access-thread-");
        // 设置拒绝策略，当队列已满时如何处理新的任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池
        executor.initialize();
        return executor;
    }
}
