springboot使用@Scheduled和@Async实现定时任务多线程并发

1.在使用定时任务的类上加@EnableScheduling和@Component两个注解。
springboot使用@Scheduled和@Async实现定时任务多线程并发_第1张图片
2.在你想开启定时任务的方法上边加上 @Scheduled(cron = “0/1 * * * * ?”)(意思每秒执行一次)。
注意:开启定时任务的方法不能传参。
在这里插入图片描述
3.定时任务的配置文件

@EnableAsync
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(50));
    }
}

4.在你想开启异步多线程的类上加上@Component

在这里插入图片描述

5.在你想启动异步多线程执行的方法上边加上 @Async(“myTaskAsyncPool”) (括号里边是自定义线程池,可不加使用默认的)

在这里插入图片描述

6.自定义线程池

package com.example.demo.Tools;

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.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义创建线程池
 */
@Configuration
@EnableAsync
public class TaskExecutePool {
    @Bean(name = "myTaskAsyncPool")
    public Executor myTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20); //核心线程数
        executor.setMaxPoolSize(50);  //最大线程数
        executor.setQueueCapacity(50000); //队列大小
        executor.setKeepAliveSeconds(300); //线程最大空闲时间
        executor.setThreadNamePrefix("async-Executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略(一共四种,此处省略)
        executor.initialize();
        return executor;
    }
}



7.在springboot启动类添加注解@EnableScheduling 和 @EnableAsync 以及在@ComponentScan里边添加你新增的添加了@Component注解的类所在的包。

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@ComponentScan(value = {"com.example.demo.test","com.example.demo.Tools"})
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

注:加@Async的方法不能和调用它的方法在同一个类!!!

你可能感兴趣的:(多线程,spring,boot,java,spring)