当前位置: 代码网 > it编程>编程语言>Java > Spring Boot使用线程池创建多线程的完整示例

Spring Boot使用线程池创建多线程的完整示例

2025年03月18日 Java 我要评论
在 spring boot 2 中,可以使用 @autowired 注入 线程池(threadpooltaskexecutor 或 executorservice),从而管理线程的创建和执行。以下是使

在 spring boot 2 中,可以使用 @autowired 注入 线程池(threadpooltaskexecutorexecutorservice),从而管理线程的创建和执行。以下是使用 @autowired 方式注入线程池的完整示例。

1. 通过 @autowired 注入 threadpooltaskexecutor

步骤 1:配置线程池

创建 threadpooltaskexecutor@bean 配置:

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;
import java.util.concurrent.executor;
@configuration
public class threadpoolconfig {
    @bean(name = "customtaskexecutor")
    public executor taskexecutor() {
        threadpooltaskexecutor executor = new threadpooltaskexecutor();
        executor.setcorepoolsize(5);  // 核心线程数
        executor.setmaxpoolsize(10);  // 最大线程数
        executor.setqueuecapacity(25); // 任务队列容量
        executor.setthreadnameprefix("async-executor-"); // 线程名前缀
        executor.initialize();
        return executor;
    }
}

步骤 2:使用 @autowired 注入线程池

service 层,通过 @autowired 注入 threadpooltaskexecutor 并执行任务:

import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;
import org.springframework.stereotype.service;
import java.util.concurrent.future;
@service
public class asynctaskservice {
    private static final logger logger = loggerfactory.getlogger(asynctaskservice.class);
      @autowired
    @qualifier("customtaskexecutor") // 通过 @qualifier 指定 bean 名称
    private threadpooltaskexecutor customtaskexecutor;
    // 提交异步任务
    public void runasynctask() {
        customtaskexecutor.execute(() -> {
            logger.info("异步任务执行,线程名:{}", thread.currentthread().getname());
            try {
                thread.sleep(2000); // 模拟耗时任务
            } catch (interruptedexception e) {
                e.printstacktrace();
            }
            logger.info("异步任务完成,线程名:{}", thread.currentthread().getname());
        });
    }
    // 提交带返回值的异步任务
    public future<string> runasynctaskwithresult() {
        return customtaskexecutor.submit(() -> {
            logger.info("执行带返回值的异步任务,线程名:{}", thread.currentthread().getname());
            thread.sleep(2000);
            return "任务完成";
        });
    }
}

步骤 3:在 controller 中调用

controller 层,通过 @autowired 调用 asynctaskservice

import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import java.util.concurrent.future;
@restcontroller
@requestmapping("/task")
public class asynctaskcontroller {
    @autowired
    private asynctaskservice asynctaskservice;
    @getmapping("/run")
    public string runtask() {
        asynctaskservice.runasynctask();
        return "任务已提交";
    }
    @getmapping("/runwithresult")
    public string runtaskwithresult() throws exception {
        future<string> result = asynctaskservice.runasynctaskwithresult();
        return "任务结果:" + result.get();
    }
}

2. 通过 @autowired 注入 threadpooltaskscheduler(适用于定时任务)

步骤 1:配置 threadpooltaskscheduler

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.concurrent.threadpooltaskscheduler;
@configuration
public class taskschedulerconfig {
    @bean
    public threadpooltaskscheduler taskscheduler() {
        threadpooltaskscheduler scheduler = new threadpooltaskscheduler();
        scheduler.setpoolsize(5);  // 线程池大小
        scheduler.setthreadnameprefix("scheduled-task-");
        scheduler.initialize();
        return scheduler;
    }
}

步骤 2:在 service 中使用 @autowired注入

import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.scheduling.concurrent.threadpooltaskscheduler;
import org.springframework.stereotype.service;
import java.util.concurrent.scheduledfuture;
@service
public class scheduledtaskservice {
    private static final logger logger = loggerfactory.getlogger(scheduledtaskservice.class);
    @autowired
    private threadpooltaskscheduler taskscheduler;
    public void scheduletask() {
        scheduledfuture<?> future = taskscheduler.scheduleatfixedrate(() -> {
            logger.info("执行定时任务,线程名:{}", thread.currentthread().getname());
        }, 5000);
    }
}

步骤 3:在 controller 中调用

import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
@requestmapping("/schedule")
public class scheduletaskcontroller {
    @autowired
    private scheduledtaskservice scheduledtaskservice;
    @getmapping("/start")
    public string startscheduledtask() {
        scheduledtaskservice.scheduletask();
        return "定时任务已启动";
    }
}

3. 通过 @autowired 注入 executorservice

如果你更喜欢 java 原生的 executorservice,可以使用 @bean 配置:

步骤 1:定义 executorservice 线程池

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
@configuration
public class executorserviceconfig {
    @bean
    public executorservice fixedthreadpool() {
        return executors.newfixedthreadpool(5);
    }
}

步骤 2:在 service 中注入 executorservice

import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.stereotype.service;
import java.util.concurrent.executorservice;
@service
public class executorservicetask {
    private static final logger logger = loggerfactory.getlogger(executorservicetask.class);
    @autowired
    private executorservice executorservice;
    public void executetask() {
        executorservice.execute(() -> {
            logger.info("执行任务,线程名:{}", thread.currentthread().getname());
        });
    }
}

步骤 3:在 controller 中调用

import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
@requestmapping("/executor")
public class executorservicecontroller {
    @autowired
    private executorservicetask executorservicetask;
    @getmapping("/run")
    public string runtask() {
        executorservicetask.executetask();
        return "任务已提交";
    }
}

总结

方式适用场景配置方式
threadpooltaskexecutor普通异步任务 (@asyncexecute)@autowired private threadpooltaskexecutor
threadpooltaskscheduler定时任务@autowired private threadpooltaskscheduler
executorservice原生 java 线程池@autowired private executorservice

推荐方式

  • 使用 threadpooltaskexecutor 结合 @autowired 来管理异步任务(推荐)。
  • 使用 threadpooltaskscheduler 进行定时任务调度。
  • 避免直接使用 executorservice,因为它不受 spring 管理,不能动态调整线程池参数。

这样可以 充分利用 spring boot 线程池管理,提高系统性能,减少资源消耗,并且代码更易维护! 🚀

到此这篇关于spring boot使用线程池创建多线程的文章就介绍到这了,更多相关spring boot线程池创建多线程内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

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