异步线程实现简单实现方式@Async
初始化配置EnableAsync
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author: wangxiaofeng
* @Description
* @date 2023/12/6 16:45
* @Version: 1.0
*/
@Configuration
@EnableAsync
public class TheadPoolConfig implements AsyncConfigurer {
@Value("${ThreadPoolConfig.corePoolSize:50}")
private int coreSize;
@Value("${ThreadPoolConfig.maxPoolSize:200}")
private int maxSize;
@Value("${ThreadPoolConfig.queueCapacity:100}")
private int queueCapacity;
@Value("${ThreadPoolConfig.keepAlive:100}")
private int keepAliveSeconds;
@Value("${ThreadPoolConfig.otherCoreSize:50}")
private int otherCoreSize;
@Value("${ThreadPoolConfig.otherMaxPoolSize:200}")
private int otherMaxSize;
@Value("${ThreadPoolConfig.otherQueueCapacity:100}")
private int otherQueueCapacity;
@Value("${ThreadPoolConfig.otherKeepAlive:100}")
private int otherKeepAliveSeconds;
@Bean("asyncThreadPool")
public AsyncTaskExecutor taskExecutor1() {
//使用Spring内置线程池任务对象
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//设置线程池参数
taskExecutor.setThreadNamePrefix("asyncThreadPool-");
taskExecutor.setCorePoolSize(coreSize);
taskExecutor.setMaxPoolSize(maxSize);
taskExecutor.setQueueCapacity(queueCapacity);
taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
使用
@Async("asyncThreadPool")
public void updateHotelPriceMap(String hotelId) {
}