SSM+Flask混合架构在古诗词数字化展演中的实践
2026/10/15 11:14:09
Spring Boot 中实现多线程的 6 种主流方式(2025-2026 实战指南)
Spring Boot 提供了非常丰富的多线程支持手段,从最简单的注解到虚拟线程(Java 21+ / 25+ 时代的主流方向),可以满足从简单异步任务到高并发 IO/CPU 密集型场景的各种需求。
下面列出目前(2026 年视角)最常用、最推荐的6 种方式,并按推荐优先级排序(从最常用 → 最前沿)。
适用场景:邮件发送、日志记录、文件上传、非核心耗时操作、异步写操作等
核心步骤:
@EnableAsync@AsyncThreadPoolTaskExecutor// 开启异步@EnableAsync@SpringBootApplicationpublicclassApplication{...}// 异步方法@ServicepublicclassMailService{@AsyncpublicvoidsendMail(Stringto,Stringcontent){// 耗时操作log.info("发送邮件中... Thread: {}",Thread.currentThread().getName());}}自定义线程池(强烈推荐):
@ConfigurationpublicclassAsyncConfigimplementsAsyncConfigurer{@OverridepublicExecutorgetAsyncExecutor(){ThreadPoolTaskExecutorexecutor=newThreadPoolTaskExecutor();executor.setCorePoolSize(8);executor.setMaxPoolSize(16);executor.setQueueCapacity(200);executor.setThreadNamePrefix("async-mail-");// 拒绝策略(很重要!)executor.setRejectedExecutionHandler(newThreadPoolExecutor.CallerRunsPolicy());executor.initialize();returnexecutor;}@OverridepublicAsyncUncaughtExceptionHandlergetAsyncUncaughtExceptionHandler(){return(ex,method,params)->log.error("异步异常",ex);}}优点:零侵入、简单
缺点:无法获取返回值(需配合 CompletableFuture)
适用场景:需要异步结果、任务编排、并行聚合、超时控制
@ServicepublicclassUserService{@AsyncpublicCompletableFuture<User>getUserById(Longid){// 模拟耗时Thread.sleep(1000);returnCompletableFuture.completedFuture(newUser(id));}publicCompletableFuture<List<User>>batchGetUsers(List<Long>ids){List<CompletableFuture<User>>futures=ids.stream().map(this::getUserById).toList();returnCompletableFuture.allOf(futures.toArray(newCompletableFuture[0])).thenApply(v->futures.stream().map(CompletableFuture::join).toList());}}优点:强大组合能力、异常处理友好
缺点:代码稍复杂
适用场景:需要精细控制线程池、批量任务、自定义拒绝策略
@AutowiredprivateThreadPoolTaskExecutorexecutor;publicvoidprocessBatch(List<Task>tasks){List<CompletableFuture<Void>>futures=newArrayList<>();for(Tasktask:tasks){CompletableFuture<Void>future=CompletableFuture.runAsync(task::execute,executor);futures.add(future);}CompletableFuture.allOf(futures.toArray(newCompletableFuture[0])).join();}适用场景:不依赖 Spring 容器、测试、工具类、极简场景
// 方式1:直接 new Thread(不推荐)newThread(()->doSomething()).start();// 方式2:Executors 工具类ExecutorServiceexecutor=Executors.newFixedThreadPool(10);executor.submit(()->doSomething());注意:生产环境强烈不建议直接用Executors.newFixedThreadPool(),因为 OOM 风险极大(无界队列)。
适用场景:高并发 IO 密集型场景(接口调用、文件读写、数据库查询等)
开启方式(Spring Boot 3.2+):
# application.ymlspring:threads:virtual:enabled:true或代码方式:
@BeanpublicTaskExecutortaskExecutor(){returnExecutors.newVirtualThreadPerTaskExecutor();}@Async 也会自动使用虚拟线程(当启用后)
优点:线程创建成本极低、可创建数十万线程、极大提升吞吐量
缺点:CPU 密集型任务不适合(仍建议用固定线程池)
适用场景:定时批量处理、爬虫、清理任务
@Configuration@EnableScheduling@EnableAsyncpublicclassScheduleConfig{@Scheduled(cron="0 */5 * * * ?")@Async("batchExecutor")publicvoidprocessBatchJob(){// 批量处理逻辑}@Bean("batchExecutor")publicThreadPoolTaskExecutorbatchExecutor(){ThreadPoolTaskExecutorexecutor=newThreadPoolTaskExecutor();executor.setCorePoolSize(4);executor.setMaxPoolSize(8);// ...returnexecutor;}}| 优先级 | 方式 | 推荐场景 | 推荐指数 |
|---|---|---|---|
| ★★★★★ | @Async + 自定义线程池 | 99% 普通异步任务 | 最高 |
| ★★★★☆ | CompletableFuture | 需要结果、编排、并行聚合 | 很高 |
| ★★★★☆ | 虚拟线程(enabled=true) | 高并发 IO 密集型 | 强烈推荐 |
| ★★★☆☆ | ThreadPoolTaskExecutor 手动 | 精细控制、批量任务 | 常用 |
| ★★☆☆☆ | Java 原生 Executors | 非 Spring 场景、测试 | 谨慎 |
| ★★☆☆☆ | @Scheduled + 多线程 | 定时批量处理 | 特定场景 |
你当前项目中主要想解决哪类多线程问题?
是接口响应慢、批量任务卡顿、还是想引入虚拟线程?可以告诉我具体场景,我可以给出更针对性的代码和调优建议。