SpringBoot 对多线程的支持

本文详细介绍如何在SpringBoot项目中配置和使用多线程,包括必要的注解、配置代码和服务实现,以及测试多线程功能的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  我们在实际项目中有些复杂运算、耗时操作,就可以利用多线程来充分利用CPU,提高系统吞吐量。SpringBoot对多线程支持非常好,对我们的开发非常便捷。

1.需要的注解

 springboot 配置多线程需要两个注解

  1. @EnableAsync
    在配置类中通过加@EnableAsync开启对异步任务的支持
  2. @Async
    在需要执行的方法上加@Async表明该方法是个异步方法,如果加在类级别上,则表明类所有的方法都是异步方法

2.配置代码

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        taskExecutor.setCorePoolSize(8);
        //最大线程数
        taskExecutor.setMaxPoolSize(16);
        //队列大小
        taskExecutor.setQueueCapacity(100);
        taskExecutor.initialize();
        return taskExecutor;
    }
}
复制代码

3.Service

@Service
public class AsyncService {

    @Async
    public void executeAsync1() {
        Thread.sleep(20);
        System.out.println("异步任务::1");

    }

    @Async
    public void executeAsync2() {
        System.out.println("异步任务::2");
    }

}

复制代码

【注】这里的方法自动被注入使用上文配置的ThreadPoolTaskExecutor

4.测试代码

    @Resource
    private AsyncService asyncService;

    @Test
    public void asyncTest() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            asyncService.executeAsync1();
            asyncService.executeAsync2();
        }
        Thread.sleep(1000);
    }
    
复制代码

5.运行结果

异步任务::2
异步任务::2
异步任务::2
异步任务::2
异步任务::2
异步任务::2
异步任务::2
异步任务::1
异步任务::1
异步任务::1
异步任务::1
异步任务::1
异步任务::1
异步任务::1
异步任务::1
异步任务::2
异步任务::2
异步任务::2
异步任务::1
异步任务::1
复制代码

【注】本文基于SpringBoot 2.0

GitHub 连接


感谢《Spring Boot实战 JavaEE开发的颠覆者》
在Spring Boot中集成Quartz并实现多线程任务调度,可以通过合理配置`application.yml`和自定义线程池来实现。以下是具体的配置方法和实现步骤: ### 1. 添加Maven依赖 首先,在项目的`pom.xml`文件中添加Spring Boot Starter Quartz的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> ``` 该依赖不仅引入了Quartz的核心库,还集成了Spring Boot的自动配置功能,使得Quartz能够与Spring生态无缝结合[^1]。 --- ### 2. 配置Quartz属性 在`application.yml`中配置Quartz的相关参数,包括线程池大小、任务调度器等: ```yaml spring: quartz: job-store-type: memory scheduler-name: MyScheduler properties: org: quartz: threadPool: class: org.quartz.simpl.SimpleThreadPool threadCount: 10 threadPriority: 5 ``` 上述配置设置了线程池为`SimpleThreadPool`,线程数量为10,优先级为5。通过这种方式可以支持多个任务并发执行,提高系统的吞吐量[^2]。 --- ### 3. 自定义线程池(可选) 如果需要更灵活的线程管理,可以自定义线程池并将其注入到Quartz的调度器中。例如: ```java import org.quartz.spi.JobFactory; import org.quartz.spi.TriggerFiredBundle; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.scheduling.quartz.SpringBeanJobFactory; import javax.sql.DataSource; import java.util.Properties; @Configuration public class QuartzConfig { @Bean public JobFactory jobFactory(AutowireCapableBeanFactory autowireCapableBeanFactory) { return new SpringBeanJobFactory(autowireCapableBeanFactory); } @Bean public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory, DataSource dataSource) { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setJobFactory(jobFactory); factory.setDataSource(dataSource); Properties props = new Properties(); props.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool"); props.put("org.quartz.threadPool.threadCount", "20"); props.put("org.quartz.threadPool.threadPriority", "5"); factory.setQuartzProperties(props); return factory; } } ``` 此配置允许开发者对线程池进行更精细的控制,并且确保每个任务实例都能正确地被Spring容器管理。 --- ### 4. 创建定时任务类 创建一个继承自`QuartzJobBean`的任务类,并重写`executeInternal`方法以定义任务逻辑: ```java import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; public class MyTask extends QuartzJobBean { @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { // 执行具体业务逻辑 System.out.println("Executing task..."); } } ``` --- ### 5. 动态注册任务 使用`Scheduler`接口动态注册任务,可以在运行时根据需求添加或删除任务: ```java import org.quartz.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component public class TaskScheduler { @Autowired private Scheduler scheduler; @PostConstruct public void scheduleTasks() throws SchedulerException { JobDetail job = JobBuilder.newJob(MyTask.class).withIdentity("myTask").storeDurably().build(); Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("myTrigger") .startNow() .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(10) .repeatForever()) .build(); scheduler.scheduleJob(job, trigger); } } ``` 此代码示例展示了如何每10秒执行一次任务,并且支持动态注册多个任务[^2]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值