当前位置: 代码网 > it编程>编程语言>Java > SpringBoot中实现多线程六种方式大全

SpringBoot中实现多线程六种方式大全

2026年02月10日 Java 我要评论
spring boot 提供了非常丰富的多线程支持手段,从最简单的注解到虚拟线程(java 21+ / 25+ 时代的主流方向),可以满足从简单异步任务到高并发 io/cpu 密集型场景的各种需求。下

spring boot 提供了非常丰富的多线程支持手段,从最简单的注解到虚拟线程(java 21+ / 25+ 时代的主流方向),可以满足从简单异步任务到高并发 io/cpu 密集型场景的各种需求。

下面列出目前(2026 年视角)最常用、最推荐的 6 种方式,并按推荐优先级排序(从最常用 → 最前沿)。

1. @async + @enableasync(最常用、最简单)

核心步骤

  1. 启动类或配置类加 @enableasync
  2. 方法加 @async
  3. (可选)自定义线程池 threadpooltaskexecutor
// 开启异步
@enableasync
@springbootapplication
public class application { ... }

// 异步方法
@service
public class mailservice {

    @async
    public void sendmail(string to, string content) {
        // 耗时操作
        log.info("发送邮件中... thread: {}", thread.currentthread().getname());
    }
}

自定义线程池(强烈推荐)

@configuration
public class asyncconfig implements asyncconfigurer {

    @override
    public executor getasyncexecutor() {
        threadpooltaskexecutor executor = new threadpooltaskexecutor();
        executor.setcorepoolsize(8);
        executor.setmaxpoolsize(16);
        executor.setqueuecapacity(200);
        executor.setthreadnameprefix("async-mail-");
        // 拒绝策略(很重要!)
        executor.setrejectedexecutionhandler(new threadpoolexecutor.callerrunspolicy());
        executor.initialize();
        return executor;
    }

    @override
    public asyncuncaughtexceptionhandler getasyncuncaughtexceptionhandler() {
        return (ex, method, params) -> log.error("异步异常", ex);
    }
}

优点:零侵入、简单
缺点:无法获取返回值(需配合 completablefuture)

2. completablefuture + @async(有返回值 + 链式编排)

适用场景:需要异步结果、任务编排、并行聚合、超时控制

@service
public class userservice {

    @async
    public completablefuture<user> getuserbyid(long id) {
        // 模拟耗时
        thread.sleep(1000);
        return completablefuture.completedfuture(new user(id));
    }

    public completablefuture<list<user>> batchgetusers(list<long> ids) {
        list<completablefuture<user>> futures = ids.stream()
            .map(this::getuserbyid)
            .tolist();

        return completablefuture.allof(futures.toarray(new completablefuture[0]))
            .thenapply(v -> futures.stream().map(completablefuture::join).tolist());
    }
}

优点:强大组合能力、异常处理友好
缺点:代码稍复杂

3. threadpooltaskexecutor 手动提交任务(最灵活)

适用场景:需要精细控制线程池、批量任务、自定义拒绝策略

@autowired
private threadpooltaskexecutor executor;

public void processbatch(list<task> tasks) {
    list<completablefuture<void>> futures = new arraylist<>();
    for (task task : tasks) {
        completablefuture<void> future = completablefuture.runasync(task::execute, executor);
        futures.add(future);
    }
    completablefuture.allof(futures.toarray(new completablefuture[0])).join();
}

4. java 原生方式(executors / thread / runnable / callable)

适用场景:不依赖 spring 容器、测试、工具类、极简场景

// 方式1:直接 new thread(不推荐)
new thread(() -> dosomething()).start();

// 方式2:executors 工具类
executorservice executor = executors.newfixedthreadpool(10);
executor.submit(() -> dosomething());

注意:生产环境强烈不建议直接用 executors.newfixedthreadpool(),因为 oom 风险极大(无界队列)。

5. 虚拟线程(java 21+ / spring boot 3.2+ / 3.3+ 强烈推荐)

适用场景:高并发 io 密集型场景(接口调用、文件读写、数据库查询等)

开启方式(spring boot 3.2+):

# application.yml
spring:
  threads:
    virtual:
      enabled: true

或代码方式:

@bean
public taskexecutor taskexecutor() {
    return executors.newvirtualthreadpertaskexecutor();
}

@async 也会自动使用虚拟线程(当启用后)

优点:线程创建成本极低、可创建数十万线程、极大提升吞吐量
缺点:cpu 密集型任务不适合(仍建议用固定线程池)

6. spring 定时任务 + 多线程(@scheduled + 线程池)

适用场景:定时批量处理、爬虫、清理任务

@configuration
@enablescheduling
@enableasync
public class scheduleconfig {

    @scheduled(cron = "0 */5 * * * ?")
    @async("batchexecutor")
    public void processbatchjob() {
        // 批量处理逻辑
    }

    @bean("batchexecutor")
    public threadpooltaskexecutor batchexecutor() {
        threadpooltaskexecutor executor = new threadpooltaskexecutor();
        executor.setcorepoolsize(4);
        executor.setmaxpoolsize(8);
        // ...
        return executor;
    }
}

推荐优先级总结(2026 年视角)

优先级方式推荐场景推荐指数
★★★★★@async + 自定义线程池99% 普通异步任务最高
★★★★☆completablefuture需要结果、编排、并行聚合很高
★★★★☆虚拟线程(enabled=true)高并发 io 密集型强烈推荐
★★★☆☆threadpooltaskexecutor 手动精细控制、批量任务常用
★★☆☆☆java 原生 executors非 spring 场景、测试谨慎
★★☆☆☆@scheduled + 多线程定时批量处理特定场景

性能提升关键点(架构层面)

  1. 异步化非核心路径(邮件、日志、推送、文件处理)
  2. 线程池参数合理调优(核心数 ≈ cpu核数*2 ~ 3,队列容量 50~200)
  3. 拒绝策略选 callerrunspolicy(防止雪崩)
  4. 异常捕获(@async 方法异常默认被吞掉)
  5. 虚拟线程优先(io 密集场景可提升 5~20 倍吞吐)
  6. 监控(micrometer + prometheus + grafana 监控线程池状态)

你当前项目中主要想解决哪类多线程问题?
是接口响应慢、批量任务卡顿、还是想引入虚拟线程?可以告诉我具体场景,我可以给出更针对性的代码和调优建议。

以上就是springboot中实现多线程六种方式大全的详细内容,更多关于springboot实现多线程方式的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com