Spring Boot 配置异步Async方法

  1. 注解启动类
@EnableAsync
@SpringBootApplication
public class LocustRunnerApplication {

    public static void main(String[] args) {
        SpringApplication.run(LocustRunnerApplication.class, args);
    }
}

  1. 添加线程池配置
@Configuration
public class AsyncConfig {

    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(8);
        executor.setQueueCapacity(200);
        executor.setThreadNamePrefix("LocustTask-");
        executor.initialize();
        return executor;
    }
}
  1. 标注异步方法-不带返回值
@Async
public void asyncMethod() {
    try {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " asyncMethod: " + i);
            Thread.sleep(1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
  1. 标注异步方法-不带返回值
@Async
public Future asyncMethodWithReturn() {
    try {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() +  " asyncMethodWithReturn: " + i);
            Thread.sleep(1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return new AsyncResult<>(Thread.currentThread().getName() + " asyncMethodWithReturn: done");
}

线程池的调用过程

  1. 核心线程池未满时: 接收任务,创建线程并执行该任务。
  2. 核心线程池已满时: 接收任务,任务进入等待队列等待。
  3. 核心线程池满且等待队列也满时: 接收任务,并创建线程执行该任务。
  4. 核心线程满,等待队列满且最大线程池也满时: 接收任务,按丢弃策略处理该任务。

你可能感兴趣的:(Spring Boot 配置异步Async方法)