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


目录
相关文章
|
5月前
|
并行计算 Java 数据处理
SpringBoot高级并发实践:自定义线程池与@Async异步调用深度解析
SpringBoot高级并发实践:自定义线程池与@Async异步调用深度解析
370 0
|
10天前
|
Java 数据库 开发者
详细介绍SpringBoot启动流程及配置类解析原理
通过对 Spring Boot 启动流程及配置类解析原理的深入分析,我们可以看到 Spring Boot 在启动时的灵活性和可扩展性。理解这些机制不仅有助于开发者更好地使用 Spring Boot 进行应用开发,还能够在面对问题时,迅速定位和解决问题。希望本文能为您在 Spring Boot 开发过程中提供有效的指导和帮助。
52 12
|
3月前
|
Java
【JavaEE】——多线程常用类
Callable的call方法,FutureTask类,ReentrantLock可重入锁和对比,Semaphore信号量(PV操作)CountDownLatch锁存器,
|
3月前
|
Java 程序员 调度
【JavaEE】线程创建和终止,Thread类方法,变量捕获(7000字长文)
创建线程的五种方式,Thread常见方法(守护进程.setDaemon() ,isAlive),start和run方法的区别,如何提前终止一个线程,标志位,isinterrupted,变量捕获
|
3月前
|
安全 Java API
【JavaEE】多线程编程引入——认识Thread类
Thread类,Thread中的run方法,在编程中怎么调度多线程
|
4月前
|
安全 Java
Java多线程集合类
本文介绍了Java中线程安全的问题及解决方案。通过示例代码展示了使用`CopyOnWriteArrayList`、`CopyOnWriteArraySet`和`ConcurrentHashMap`来解决多线程环境下集合操作的线程安全问题。这些类通过不同的机制确保了线程安全,提高了并发性能。
|
5月前
|
算法 NoSQL Java
Springboot3新特性:GraalVM Native Image Support和虚拟线程(从入门到精通)
这篇文章介绍了Spring Boot 3中GraalVM Native Image Support的新特性,提供了将Spring Boot Web项目转换为可执行文件的步骤,并探讨了虚拟线程在Spring Boot中的使用,包括如何配置和启动虚拟线程支持。
274 9
Springboot3新特性:GraalVM Native Image Support和虚拟线程(从入门到精通)
|
5月前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
149 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
5月前
lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O
Lua的面向对象编程、协同线程与协同函数的概念和使用,以及Lua文件I/O操作的基本方法。
76 4
lua面向对象(类)和lua协同线程与协同函数、Lua文件I/O
|
4月前
|
前端开发 Java 数据格式
SpringBoot中定义Bean的几种方式
本文介绍了Spring Boot中定义Bean的多种方式,包括使用@Component、@Bean、@Configuration、@Import等注解及Java配置类。每种方式适用于不同的场景,帮助开发者高效管理和组织应用组件。