【2020年最后一篇日志】SpringBoot中用多线程执行定时任务

刚开始接触SpringBoot的时候就想用多线程执行一些定时任务,但是一直没有实现,因为它总是在run方法中提示注入的资源是无效的。让人头疼,一直没有好的解决办法。直到今天才发现他的解决办法-异步执行多线程。

  • 启动方式
    @Scheduled(cron = "*/10 * * * * ?") // 每秒钟启动 0 0 23 * * ? 0 */1 * * * ? 0 0 8 * * ?
	public void trackMailedJob() {
		
		for (int i = 0; i < 10; i++) {
			TestThread2 testThread2 = new TestThread2();
			testThread2.start();
		}
	}
  • 报错如下 jdbcTemplate是null
    在这里插入图片描述

  • 之后我又换了一种方式,没报错,但是不是多线程
    在这里插入图片描述

真正使用多线程的方式如下!
  • 先写这样一个配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
import java.util.concurrent.ThreadPoolExecutor;
 
@Configuration
@EnableAsync
public class AsyncConfig {
 
    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(6);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("test-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
 
}
  • 写一个定时任务
@Log
@Component
public class TrackJobThreads {

	@Autowired
	private TestThread2 testThread;

	@Scheduled(cron = "*/37 * * * * ?") // 每秒钟启动 0 0 23 * * ? 0 */1 * * * ? 0 0 8 * * ?
	public void trackMailedJob() {
		 //  10个线程是不起效的 它取决于 executor.setCorePoolSize(6);
		 // 所以才有下面的打印结果  线程数不超过6个
		for (int i = 0; i < 10; i++) {
			testThread.run();  
     
		}
	}
}
  • 核心-多线程类TestThread2
@Async
	public synchronized void run() {
		log.info("你好呀"+TimeUtil.transfLongToTimeStr(Clock.systemUTC().millis()));
		try {
			Thread.currentThread().sleep(1000l);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
  • 运行结果:

在这里插入图片描述

  • 成功了,再见了2020.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱吃早餐的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值