springboot单类集中定义线程池

简介: 该内容是关于Spring中异步任务的配置和使用步骤。首先,在启动类添加`@EnableAsync`注解开启异步支持。然后,自定义线程池类`EventThreadPool`,设置核心和最大线程数、存活时间等参数。接着,将线程池bean注入到Spring中,如`@Bean("RewardThreadPool")`。最后,在需要异步执行的方法上使用`@Async`注解,例如在一个定时任务类中,使用`@Scheduled(cron = "...")`和`@Async`结合实现异步定时任务。

 1、在启动类上加注解  @EnableAsync

2、定义线程池的类

package com.javabase.Thread;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
public class EventThreadPool extends ThreadPoolExecutor {
    /**
     * 定义线程工厂名称
     */
    private static ThreadFactory HANDLEREMINDWAY_FACTORY = new ThreadFactoryBuilder()
            .setNameFormat("EventThreadPool-%d").build();
    public EventThreadPool() {
        super(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 30,
                20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000), HANDLEREMINDWAY_FACTORY,new CallerRunsPolicy());
    }
//    public ThreadPoolExecutor getThreadPoolExecutor() {
//        return new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 30,
//            20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
//    }
    public EventThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        /**
         *
         * (ArrayBlockingQueue读写只有一个锁(效率更高),LinkedBlockingQueue读写锁分离)
         * LinkedBlockingQueue即无界队列.
         * 将ArrayBlockingQueue即无界队列的大小设置为1000.
         * 使用无界队列
         * 将LinkedBlockingQueue即无界队列的大小设置为500.
         * 将导致在所有 corePoolSize线程都忙的情况下将新任务加入队列,
         * 这样,创建的线程就不会超过 corePoolSize, 而且当排队的任务超过500时,将拒绝执行
         */
        super(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000), Executors
                .defaultThreadFactory());
    }
}

image.gif

3、注入工厂到spring中

package com.javabase.Thread;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class ThreadPoolConfig {
    @Bean("RewardThreadPool")
    public ThreadPoolExecutor rewardThreadPool() {
        return new EventThreadPool();
    }
    @Bean("reportThreadPool")
    public ThreadPoolExecutor reportThreadPool() {
        return new EventThreadPool();
    }
    @Bean("roomReservationThreadPool")
    public ThreadPoolExecutor roomReservationThreadPool() {
        return new EventThreadPool();
    }
}

image.gif

4、在自己的方法中使用

package com.javabase.Thread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
 * 构建执行定时任务
 * TODO
 */
@Component
@EnableScheduling
public class ScheduledTask3 {
    private Logger logger = LoggerFactory.getLogger(ScheduledTask3.class);
 
    private int fixedDelayCount = 1;
    private int fixedRateCount = 1;
    private int initialDelayCount = 1;
    private int cronCount = 1;
 
  /*  @Scheduled(fixedDelay = 5000)        //fixedDelay = 5000表示当前方法执行完毕5000ms后,Spring scheduling会再次调用该方法
    public void testFixDelay() {
        logger.info("===fixedDelay: 第{}次执行方法", fixedDelayCount++);
    }
 
    @Scheduled(fixedRate = 5000)        //fixedRate = 5000表示当前方法开始执行5000ms后,Spring scheduling会再次调用该方法
    public void testFixedRate() {
        logger.info("===fixedRate: 第{}次执行方法", fixedRateCount++);
    }
 
    @Scheduled(initialDelay = 1000, fixedRate = 5000)   //initialDelay = 1000表示延迟1000ms执行第一次任务
    public void testInitialDelay() {
        logger.info("===initialDelay: 第{}次执行方法", initialDelayCount++);
    }*/
 
    /*@Scheduled(cron = "0 0/1 * * * ?")  //cron接受cron表达式,根据cron表达式确定定时规则
    public void testconfigureTasks() {
        logger.info("===initialDelay: 第{}次执行方法", cronCount++);
    }*/
    @Async("RewardThreadPool")
    @Scheduled(cron = "0/1 * * * * ?")
    public void testtaskExecutor() {
        logger.info("ScheduledTask3定时任务开始 :{} " + "\r\n线程 : {}", LocalDateTime.now().toLocalTime(), Thread.currentThread().getName());
        logger.info("===initialDelay: 第{}次执行方法", cronCount++);
    }
}

image.gif


目录
相关文章
|
8天前
|
安全 Java
并发编程之常见线程安全类以及一些示例的详细解析
并发编程之常见线程安全类以及一些示例的详细解析
13 0
|
29天前
|
Java 调度 Spring
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
271 0
|
2月前
|
安全 Java easyexcel
【二十七】springboot实现多线程事务处理
【二十七】springboot实现多线程事务处理
84 0
|
4天前
|
安全 Java 开发者
【JAVA】哪些集合类是线程安全的
【JAVA】哪些集合类是线程安全的
|
2月前
|
存储 缓存 安全
【C/C++ 关键字 存储类说明符 】 线程局部变量的魔法:C++ 中 thread_local的用法
【C/C++ 关键字 存储类说明符 】 线程局部变量的魔法:C++ 中 thread_local的用法
34 0
|
19天前
|
存储 安全 Java
多线程编程常见面试题讲解(锁策略,CAS策略,synchronized原理,JUC组件,集合类)(下)
多线程编程常见面试题讲解(锁策略,CAS策略,synchronized原理,JUC组件,集合类)(下)
43 0
|
19天前
|
存储 安全 Java
多线程编程常见面试题讲解(锁策略,CAS策略,synchronized原理,JUC组件,集合类)(上)
多线程编程常见面试题讲解(锁策略,CAS策略,synchronized原理,JUC组件,集合类)
35 0
|
21天前
|
存储 安全 Java
java多线程之原子操作类
java多线程之原子操作类
|
23天前
|
Java
Java中的多线程实现:使用Thread类与Runnable接口
【4月更文挑战第8天】本文将详细介绍Java中实现多线程的两种方法:使用Thread类和实现Runnable接口。我们将通过实例代码展示如何创建和管理线程,以及如何处理线程同步问题。最后,我们将比较这两种方法的优缺点,以帮助读者在实际开发中选择合适的多线程实现方式。
24 4
|
29天前
|
Java 应用服务中间件
Springboot启动的时候初始化的线程池默认配置tomcat
Springboot启动的时候初始化的线程池默认配置tomcat
15 1