个人感觉,@Asyn和@scheduled是springboot对jdk中ThreadpoolExecutor和ScheduledThreadpoolExecutor的再次封装。它们在springboot中分别是ThreadPoolTaskExecutor和ThreadPoolTaskScheduled.
使用方法
- 创建配置类,实现AsyncConfigurer接口,实现方法getAsyncExecutor(),
- 自定义线程池。默认情况下ThreadPoolTaskExecutor是只有一个线程的,所以要自定义线程池。
- 同时可以定义多个线程池,有任务时可以使用不同线程池中的线程。
- 使用@EnableAsync注解标注类,开启Async功能。
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
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 TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
/*
默认值
private int corePoolSize = 1;
private int maxPoolSize = Integer.MAX_VALUE;
private int queueCapacity = Integer.MAX_VALUE;
*/
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(20);
taskExecutor.setQueueCapacity(10);
taskExecutor.initialize();
return taskExec