Java 线程池 如何科学配置

⽹上查询线程池核⼼数配置,⼤部分都是这样的

注:IO密集型(某⼤⼚实践经验)核⼼线程数= CPU核数/(1-阻塞系数)

或着

CPU密集型:核⼼线程数 = CPU核数+1

IO密集型:核⼼线程数 = CPU核数*2

/**
 * 简单配置示例
 */
 
//获取当前机器的核数
public static final int cpuNum = Runtime.getRuntime().availableProcessors();
 
@Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(cpuNum);//核心线程大小
        taskExecutor.setMaxPoolSize(cpuNum * 2);//最大线程大小
        taskExecutor.setQueueCapacity(500);//队列最大容量
        //当提交的任务个数大于QueueCapacity,就需要设置该参数,但spring提供的都不太满足业务场景,可以自定义一个,也可以注意不要超过QueueCapacity即可
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(60);
        taskExecutor.setThreadNamePrefix("BCarLogo-Thread-");
        taskExecutor.initialize();
        return taskExecutor;
    }
 

你可能感兴趣的:(java,开发语言,前端)