SpringBoot最简多线程配置教程

spring 文章 2021-04-30 13:27 371 0 全屏看文

AI助手支持GPT4.0

package cn.sanshu.soa.distributionserialcenter.core.threadpool;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class ExecutorConfig {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);

    private int corePoolSize = 20;
    private int maxPoolSize = 20;
    private int queueCapacity = 9999;
    private String namePrefix = "dsc_";

    @Bean(name = "asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        logger.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}


在需要多线程调用的方法上面追加:

@Async("asyncServiceExecutor")
private void updateSaleRebateMsg() {
	syso("多线程执行方法")
}


这样就好了。

要注意 第二段代码里的 注解里的asyncServiceExecutor 一定要和第一段代码里的 bean的name相同。


-EOF-

AI助手支持GPT4.0