欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringBoot定时任务多线程实现示例

时间:2022-12-17 09:50:17|栏目:JAVA代码|点击:

测试Spring Boot定时任务冲突时,使用的线程数量

引入依赖:

Spring Boot 2.6.1

 <dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
 </dependency>

简单的测试类

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author Song Jiangtao
 * @date 2021/12/22
 * @description:
 */
@Component
@Slf4j
public class Task {

    @Scheduled(cron="*/2 * * * * ?")
    public void process(){
        log.info("do something");
    }

    @Scheduled(fixedRate = 2000)
    public void currentTime(){
        log.info("做点什么");
    }
}

启动类开启定时任务:@EnableScheduling

测试结果如下:

在这里插入图片描述

由结果可见,main线程启动以后和scheduling-1线程跑了两个任务

由此可见,Spring Boot 定时器 默认是 单线程

我们新增两个定时任务来看看这样会有什么后果

@Scheduled(cron="*/2 * * * * ?")
public void process2() throws InterruptedException {
     Thread.sleep(5000L);
     log.info("do something use long time");
 }
 @Scheduled(cron="*/2 * * * * ?")
 public void process3() throws InterruptedException {
     Thread.sleep(10000L);
     log.info("do something use long long time");
 }
2021-12-22 16:30:28.735  INFO 14520 --- [           main] c.e.s.SpringBootScheduledApplication     : Starting SpringBootScheduledApplication using Java 1.8.0_202 on TCZ-D with PID 14520 (D:\code\SpringBootScheduled\target\classes started by Administrator in D:\code\SpringBootScheduled)
2021-12-22 16:30:28.738  INFO 14520 --- [           main] c.e.s.SpringBootScheduledApplication     : No active profile set, falling back to default profiles: default
2021-12-22 16:30:29.315  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:29.318  INFO 14520 --- [           main] c.e.s.SpringBootScheduledApplication     : Started SpringBootScheduledApplication in 0.937 seconds (JVM running for 3.068)
2021-12-22 16:30:30.002  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : do something
2021-12-22 16:30:40.003  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : do something use long long time
2021-12-22 16:30:45.005  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : do something use long time
2021-12-22 16:30:45.005  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:45.005  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : do something
2021-12-22 16:30:45.006  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:45.006  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:45.006  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:45.006  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:45.006  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:55.006  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : do something use long long time
2021-12-22 16:30:55.006  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:55.006  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:30:55.007  INFO 14520 --- [   scheduling-1] c.e.springbootscheduled.scheduled.Task   : do something

很明显任务会发生错乱,严重时会导致线程阻塞,最后崩溃

解决方法:引入线程池

新增配置类,配置线程池

package com.example.springbootscheduled.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Song Jiangtao
 * @date 2021/12/22
 * @description:
 */
@Configuration
@EnableAsync
public class TaskConfig {

    /**
     * 默认线程数
     */
    private static final int corePoolSize = 10;
    /**
     * 最大线程数
     */
    private static final int maxPoolSize = 100;
    /**
     * 允许线程空闲时间(单位:默认为秒),十秒后就把线程关闭
     */
    private static final int keepAliveTime = 10;
    /**
     * 缓冲队列数
     */
    private static final int queueCapacity = 200;
    /**
     * 线程池名前缀
     */
    private static final String threadNamePrefix = "task-thread-";

    /**
     * bean的名称,默认为 首字小写 方法名
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor getThread() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(keepAliveTime);
        executor.setKeepAliveSeconds(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        //线程池拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

每个定时任务添加注解 @Async("taskExecutor")

@Async("taskExecutor")
@Scheduled(fixedRate = 2000)
public void currentTime(){
    log.info("做点什么");
}

启动测试

2021-12-22 16:41:36.141  INFO 19424 --- [           main] c.e.s.SpringBootScheduledApplication     : Starting SpringBootScheduledApplication using Java 1.8.0_202 on TCZ-D with PID 19424 (D:\code\SpringBootScheduled\target\classes started by Administrator in D:\code\SpringBootScheduled)
2021-12-22 16:41:36.143  INFO 19424 --- [           main] c.e.s.SpringBootScheduledApplication     : No active profile set, falling back to default profiles: default
2021-12-22 16:41:36.991  INFO 19424 --- [           main] c.e.s.SpringBootScheduledApplication     : Started SpringBootScheduledApplication in 1.325 seconds (JVM running for 3.392)
2021-12-22 16:41:37.008  INFO 19424 --- [  task-thread-1] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:41:38.001  INFO 19424 --- [  task-thread-2] c.e.springbootscheduled.scheduled.Task   : do something
2021-12-22 16:41:38.991  INFO 19424 --- [  task-thread-5] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:41:40.003  INFO 19424 --- [  task-thread-8] c.e.springbootscheduled.scheduled.Task   : do something
2021-12-22 16:41:40.991  INFO 19424 --- [  task-thread-9] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:41:42.001  INFO 19424 --- [ task-thread-10] c.e.springbootscheduled.scheduled.Task   : do something
2021-12-22 16:41:42.989  INFO 19424 --- [  task-thread-5] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:41:43.002  INFO 19424 --- [  task-thread-3] c.e.springbootscheduled.scheduled.Task   : do something use long time
2021-12-22 16:41:44.002  INFO 19424 --- [  task-thread-9] c.e.springbootscheduled.scheduled.Task   : do something
2021-12-22 16:41:44.990  INFO 19424 --- [  task-thread-5] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:41:45.002  INFO 19424 --- [  task-thread-6] c.e.springbootscheduled.scheduled.Task   : do something use long time
2021-12-22 16:41:46.001  INFO 19424 --- [  task-thread-9] c.e.springbootscheduled.scheduled.Task   : do something
2021-12-22 16:41:46.990  INFO 19424 --- [  task-thread-6] c.e.springbootscheduled.scheduled.Task   : 做点什么
2021-12-22 16:41:47.002  INFO 19424 --- [  task-thread-1] c.e.springbootscheduled.scheduled.Task   : do something use long time
2021-12-22 16:41:48.002  INFO 19424 --- [  task-thread-4] c.e.springbootscheduled.scheduled.Task   : do something use long long time

上一篇:Java-Java5.0注解全面解读

栏    目:JAVA代码

下一篇:JVM内存结构划分实例解析

本文标题:SpringBoot定时任务多线程实现示例

本文地址:http://www.codeinn.net/misctech/221545.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有