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


目录
相关文章
|
并行计算 Java 数据处理
SpringBoot高级并发实践:自定义线程池与@Async异步调用深度解析
SpringBoot高级并发实践:自定义线程池与@Async异步调用深度解析
943 0
|
2月前
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
187 1
|
2月前
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
212 1
|
10月前
|
Java 数据库 开发者
详细介绍SpringBoot启动流程及配置类解析原理
通过对 Spring Boot 启动流程及配置类解析原理的深入分析,我们可以看到 Spring Boot 在启动时的灵活性和可扩展性。理解这些机制不仅有助于开发者更好地使用 Spring Boot 进行应用开发,还能够在面对问题时,迅速定位和解决问题。希望本文能为您在 Spring Boot 开发过程中提供有效的指导和帮助。
1248 12
|
9月前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot中的全局异常处理——定义返回的统一 json 结构
本课主要讲解Spring Boot中的全局异常处理方法。在项目开发中,各层操作难免会遇到各种异常,若逐一处理将导致代码耦合度高、维护困难。因此,需将异常处理从业务逻辑中分离,实现统一管理与友好反馈。本文通过定义一个简化的JsonResult类(含状态码code和消息msg),结合全局异常拦截器,展示如何封装并返回标准化的JSON响应,从而提升代码质量和用户体验。
250 0
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
556 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
安全 Java
Java多线程集合类
本文介绍了Java中线程安全的问题及解决方案。通过示例代码展示了使用`CopyOnWriteArrayList`、`CopyOnWriteArraySet`和`ConcurrentHashMap`来解决多线程环境下集合操作的线程安全问题。这些类通过不同的机制确保了线程安全,提高了并发性能。
213 1
|
12月前
|
Java
【JavaEE】——多线程常用类
Callable的call方法,FutureTask类,ReentrantLock可重入锁和对比,Semaphore信号量(PV操作)CountDownLatch锁存器,
|
12月前
|
Java 程序员 调度
【JavaEE】线程创建和终止,Thread类方法,变量捕获(7000字长文)
创建线程的五种方式,Thread常见方法(守护进程.setDaemon() ,isAlive),start和run方法的区别,如何提前终止一个线程,标志位,isinterrupted,变量捕获
|
12月前
|
安全 Java API
【JavaEE】多线程编程引入——认识Thread类
Thread类,Thread中的run方法,在编程中怎么调度多线程