Spring Boot 中自定义线程池的正确使用姿势:定义、注入与最佳实践

文章目录

  • 线程池
    • [1. 定义线程池](#1. 定义线程池)
    • [2. 注入线程池](#2. 注入线程池)

线程池

1. 定义线程池

  • 定义线程池工具类value起别名
java 复制代码
@Component
public class ThreadUtil {

    @Bean("executorService")
    public ExecutorService executorService() {
        return new ThreadPoolExecutor(
                10,                    // 核心线程数
                30,                    // 最大线程数
                60, TimeUnit.SECONDS,  // 空闲线程存活时间
                new ArrayBlockingQueue<>(500), // 有界队列
                new ThreadFactory() {  // 自定义线程名
                    private final AtomicInteger index = new AtomicInteger(1);
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "task-pool-" + index.getAndIncrement());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );
    }
}

2. 注入线程池

  • 注入线程池,要用@Qualifier来与value的值对应
  • @Resource()
java 复制代码
@Service
public class TaskService {

    @Resource(name = "executorService")
    private ExecutorService executorService;

    public void doTask() {
        executorService.execute(() -> {
            System.out.println("执行任务 → " + Thread.currentThread().getName());
        });
    }
}
  • @AutoWrite()
java 复制代码
@Service
public class TaskService {

    @Autowired
    @Qualifier("executorService")
    private ExecutorService executorService;

}
  • 构造器注入
java 复制代码
@Service
public class TaskService {

    private final ExecutorService executorService;

    public TaskService(@Qualifier("executorService") ExecutorService executorService) {
        this.executorService = executorService;
    }
}
相关推荐
斯特凡今天也很帅8 分钟前
python测试SFTP连通性
开发语言·python·ftp
sunywz11 分钟前
【JVM】(4)JVM对象创建与内存分配机制深度剖析
开发语言·jvm·python
wheelmouse778813 分钟前
如何设置VSCode打开文件Tab页签换行
java·python
yangminlei15 分钟前
Spring Boot——日志介绍和配置
java·spring boot
云上凯歌19 分钟前
02 Spring Boot企业级配置详解
android·spring boot·后端
0思必得020 分钟前
[Web自动化] Selenium基础介绍
前端·python·selenium·自动化·web自动化
廋到被风吹走22 分钟前
【Spring】Spring Boot Starter设计:公司级监控SDK实战指南
java·spring boot·spring
秋饼32 分钟前
【手撕 @EnableAsync:揭秘 SpringBoot @Enable 注解的魔法开关】
java·spring boot·后端
IT_陈寒40 分钟前
Python 3.12 新特性实战:这5个改进让我的开发效率提升40%
前端·人工智能·后端
利兄的视界41 分钟前
一步到位:M4 芯片 Mac 安装 PostgreSQL 16 并适配 pgvector 教程
后端·postgresql