1、添加application.yml,设置数据

async:
  executor:
    ##核心线程数
    corePoolSize: 10
    ##最大线程数
    maxPoolSize: 10
    ##线程池中的线程的名称前缀
    prefix: async-
    ##队列大小
    queueCapacity: 10000

1、配置线程池配置类

创建一个线程池的配置,让Spring Boot加载,使用@Configuration和@EnableAsync这两个注解,表示这是线程池配置类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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 AsyncPoolConfig {
​
    private static final Logger logger = LoggerFactory.getLogger(AsyncPoolConfig.class);
​
   @Value("${async.executor.corePoolSize}")
    private int corePoolSize;
    @Value("${async.executor.maxPoolSize}")
    private int maxPoolSize;
    @Value("${async.executor.queueCapacity}")
    private int queueCapacity;
    @Value("${async.executor.prefix}")
    private String prefix;
​
    @Bean(name = "asyncServiceAsyncPool")
    public Executor asyncServiceAsyncPool() {
        logger.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(prefix);
        
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

2、创建异步调用接口以及实现类

public interface AsyncService {
    /**
     * 执行异步任务
     * 可以根据需求测试
     */
    void executeAsync();
}

实现类

@Service
public class AsyncServiceImpl implements AsyncService {
    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Override
    @Async("asyncServiceAsyncPool")
    public void executeAsync() {
        logger.info("start executeAsync");

        System.out.println("异步线程要做的事情");
        logger.info("end executeAsync");
    }
}

@Async(“asyncServiceExecutor”)表示指定使用asyncServiceExecutor线程池异步执行该方法,就是@Bean里边定义的名称

3、调用异步方法测试

创建Controller通过注解@Autowired注入这个Service

@Autowired
private AsyncService asyncService;

@GetMapping("/async")
public void async(){
    asyncService.executeAsync();
}