1. 使用ThreadFactoryBuilder设置线程名需要引入依赖
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>31.0.1-jre</version> </dependency>
2. 编写配置类
@Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { /** * 自定义线程池 * corePoolSize: 核心线程 32 个 * maximumPoolSize: 最大线程数 64 个 * keepAliveTime: 保持活性时间 30 * unit: 时间单位 * workQueue: 队列 * nameThreadFactory: 设置线程名 * handler: 拒绝策略 * * 执行流程: * 1.当提交了一个任务,查看当前是否达到核心线程数,没有达到,创建线程执行 * 2.达到了核心线程数,查看队列是否已满,未满,放入队列 * 3.满了,查看是否达到最大线程数,未达到,创建线程执行任务 * 4.已达到最大线程数,执行拒绝 * * 拒绝策略: * 1.AbortPolicy: 默认策略,直接抛出异常 * 2.CallRunsPolicy: 用调用者所在线程执行任务 * 3.DisCardOldestPolicy: 丢弃阻塞队列的头部任务,执行当前任务 * 4.DsicardPolicy: 直接丢弃任务 */ @Override public Executor getAsyncExecutor() { // 设置线程名 ThreadFactory nameThreadFactory = new ThreadFactoryBuilder().setNameFormat("async-pool-%d").build(); return new ThreadPoolExecutor(32, 64, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(128), nameThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy()); } }
3. 测试
@Service public class AsyncService { @Async public void testAsync() { System.out.println(Thread.currentThread().getName() + " 正在执行任务..."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } @RestController public class AsyncController { @Autowired private AsyncService asyncService; @GetMapping("/async/test") public void asyncTest() { asyncService.testAsync(); } }
4. 打印结果如下