原文出处 https://www.cnblogs.com/fulongyuanjushi/p/15856660.html
记录一下自己对异步线程池的使用,全部都是参考的原文。
1.定义线程池配置类,自定义线程池
import lombok.extern.slf4j.Slf4j; 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; /** * 类名称:ExecutorConfig * ******************************** * <p> * 类描述:线程池配置 * * @author guoj * @date 2021-09-07 09:00 */ @Configuration @EnableAsync @Slf4j public class ExecutorConfig { /** * 定义线程池 * * @return */ @Bean("noticeExecutor") public Executor noticeExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 核心线程数量:当前机器的核心数 executor.setCorePoolSize( Runtime.getRuntime().availableProcessors()); // 最大线程数 executor.setMaxPoolSize( Runtime.getRuntime().availableProcessors() * 2); // 队列大小 executor.setQueueCapacity(Integer.MAX_VALUE); // 线程池中的线程名前缀 executor.setThreadNamePrefix("sjsb-"); // 拒绝策略:直接拒绝 executor.setRejectedExecutionHandler( new ThreadPoolExecutor.AbortPolicy()); // 执行初始化 executor.initialize(); return executor; } }
2.编写异步服务
@Slf4j @Service public class AsyncService { /** * 异步请求路由下发回调 * */ @Async("noticeExecutor") public void notice(String str) { // log.info("[异步线程] ========进入方法"); //todo // log.info("[异步线程] ========执行完毕"); } }
3.代码中的使用
@Autowired
AsyncService asyncService;
asyncService.notice("hello");