第一步,添加配置类:
@Configuration
@EnableAsync
@Slf4j
public class ExecutorConfig {
private int corePoolSize = 10;
private int maxPoolSize = 20;
private static final int keepAliveTime = 60;
private int queueCapacity = 10;
@Bean
public Executor asyncServiceExecutor(){
log.info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(corePoolSize);
//配置最大线程数
executor.setMaxPoolSize(maxPoolSize);
//配置空闲时间
executor.setKeepAliveSeconds(keepAliveTime);
//配置队列大小
executor.setQueueCapacity(queueCapacity);
//配置线程前缀名
executor.setThreadNamePrefix("async-service-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
第二步,写需要异步处理的接口
public interface AsyncService {
void executeAsync();
}
第三步,写接口的实现类,并在实现的方法上方添加@Async(“asyncServiceExecutor”) ,括号里的asyncServiceExecutor是前面ExecutorConfig.java中的方法名,表明executeAsync方法使用asyncServiceExecutor方法创建的线程池多线程执行。之后实现的方法内部撰写需要进行异步处理的代码块:
@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {
//异步多线程调用
@Async("asyncServiceExecutor")
public void executeAsync() {
log.info("start executeAsync");
try{
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
log.info("end executeAsync");
}
}



