自定义线程池

本文介绍了《阿里巴巴JAVA开发手册》中关于避免使用Executors创建线程池的原因,并详细分析了FixedThreadPool、SingleThreadPool、CachedThreadPool和ScheduledThreadPool可能导致的OOM问题。接着,文章通过两种方式演示了如何自定义线程池,包括指定线程池名称和实现AsyncConfigurer接口的方法,提供了配置、测试等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义线程池

一.前置知识

《阿里巴巴JAVA开发手册》有这样一条强制规定:线程池不允许使用Executors去创建,而应该通过ThreadPoolExecutor方式,这样处理方式更加明确线程池运行规则,规避资源耗尽风险,能助于排查问题.

JVM调优排查问题可以看我这篇文章:暂时还没写完☺

FixedThreadPool SingleThreadPool
允许请求队列长度为Integer.MAX_VALUE可能会堆积大量请求从而导致OOM

CachedThreadPool ScheduledThreadPool
允许创建线程数量为Integer.MAX_VALUE可能会创建大量线程从而导致OOM

Fixed和Single两个线程池使用链表实现的阻塞队列,不设大小理论上队列容量无上限,所以可能会堆积大量请求从而导致OOM
Cached和Scheduled两个线程池maxSize使用Integer最大值,所以可能会创建大量线程从而导致OOM

Executors
让我们再看看Executors提供的那几个工厂方法。

newSingleThreadExecutor
创建一个单线程的线程池。这个线程池只有一个线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。
此线程池保证所有任务的执行顺序按照任务的提交顺序执行。

new ThreadPoolExecutor(1, 1,0L,TimeUnit.MILLISECONDS,new
LinkedBlockingQueue())

newFixedThreadPool
创建固定大小的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。
线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。

new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());

newCachedThreadPool
创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,
那么就会回收部分空闲(60秒不执行任务)的线程,当任务数增加时,此线程池又可以智能的添加新线程来处理任务。
此线程池不会对线程池大小做限制,线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小。

new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,new
SynchronousQueue());

二.实操

方式一:

这种需要指定线程池名称

  1. 编写配置文件
# 线程池配置参数
task:
  pool:
    corePoolSize: 10 # 设置核心线程数
    maxPoolSize: 20  # 设置最大线程数
    keepAliveTime: 300 # 设置空闲线程存活时间(秒)
    queueCapacity: 100 # 设置队列容量
    threadNamePrefix: "gblfy-signpolicy-asynnotify-" # 设置线程名称前缀
    awaitTerminationSeconds: 60 #  设置线程池等待终止时间()
spring:
  main:
    allow-bean-definition-overriding: true
  1. 编写配置类
@Data
@ConfigurationProperties(prefix = "task.pool")
@Component
public class MyThreadPoolConfig {
    /**
     * 核心线程数
     */
    private Integer corePoolSize;
    /**
     * 最大线程数
     */
    private Integer maxPoolSize;
    /**
     * 临时线程存活时间
     */
    private Integer keepAliveTime;
    /**
     * 设置队列容量
     */
    private Integer queueCapacity;
    /**
     * 设置线程名称前缀
     */
    private String threadNamePrefix;
    /**
     * 设置线程池等待终止时间(秒)
     */
    private Integer awaitTerminationSeconds;
  1. 自定义线程池
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

@Configuration
public class MyThreadFactory {

    @Autowired
    private MyThreadPoolConfig config;

    @Bean("myThreadPool")
    public Executor threadPoolExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(config.getCorePoolSize());
        //设置最大线程数
        executor.setMaxPoolSize(config.getMaxPoolSize());
        //设置空闲线程存活时间
        executor.setKeepAliveSeconds(config.getKeepAliveTime());
        //设置队列大小
        executor.setQueueCapacity(config.getQueueCapacity());
        //设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
        executor.setAwaitTerminationSeconds(config.getAwaitTerminationSeconds());
        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //线程池名的前缀
        executor.setThreadNamePrefix(config.getThreadNamePrefix());

		/**
         * 阻塞队列:
         *
         * ArrayBlockingQueue :一个由数组结构组成的有界阻塞队列。
         * LinkedBlockingQueue :一个由链表结构组成的有界阻塞队列。
         * PriorityBlockingQueue :一个支持优先级排序的无界阻塞队列。
         * DelayQueue: 一个使用优先级队列实现的无界阻塞队列。
         * SynchronousQueue: 一个不存储元素的阻塞队列。
         * LinkedTransferQueue: 一个由链表结构组成的无界阻塞队列。
         * LinkedBlockingDeque: 一个由链表结构组成的双向阻塞队列。
         *
         */

        /**
         * 拒绝处理策略
         * CallerRunsPolicy():交由调用方线程运行,比如 main 线程。
         * AbortPolicy():直接抛出异常。
         * DiscardPolicy():直接丢弃。
         * DiscardOldestPolicy():丢弃队列中最老的任务。
         */
        /**
         * 特殊说明:
         * 1. 这里演示环境,拒绝策略咱们采用抛出异常
         * 2.真实业务场景会把缓存队列的大小会设置大一些,
         * 如果,提交的任务数量超过最大线程数量或将任务环缓存到本地、redis、mysql中,保证消息不丢失
         * 3.如果项目比较大的话,异步通知种类很多的话,建议采用MQ做异步通知方案
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //线程初始化
        executor.initialize();
        return executor;


    }
}

  1. 测试
    • Service类
@Service
public class TestService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestService.class);

    @Async("myThreadPool")
    public void eat(){
        System.out.println("吃饭");
        LOGGER.info("当前线程名称:{}",Thread.currentThread().getName());
    }
}
@Service
public class TestService2 {


    private static final Logger LOGGER = LoggerFactory.getLogger(TestService2.class);

    @Async("myThreadPool")
    public void eat(){
        System.out.println("吃饭2");
        LOGGER.info("当前线程名称:{}",Thread.currentThread().getName());
    }
}
  • controller
@RestController
public class TestController {
    @Autowired
    private TestService testService;
    @Autowired
    private TestService2 testService2;

    @RequestMapping("/thread")
    public void  test(){
        testService.eat();
        testService2.eat();
    }
}

输出结果为:

吃饭
吃饭2
2022-08-30 15:37:17.840  INFO 29484 --- [cy-asynnotify-1] c.y.testMyThreadPool.TestService         : 当前线程名称:gblfy-signpolicy-asynnotify-1
2022-08-30 15:37:17.840  INFO 29484 --- [cy-asynnotify-2] c.y.testMyThreadPool.TestService2        : 当前线程名称:gblfy-signpolicy-asynnotify-2

方式二:

这种不需要指定线程池名称,通过实现AsyncConfigurer接口,重新里面的方法

  1. 编写配置文件
# 线程池配置参数
task:
  pool:
    corePoolSize: 10 # 设置核心线程数
    maxPoolSize: 20  # 设置最大线程数
    keepAliveTime: 300 # 设置空闲线程存活时间(秒)
    queueCapacity: 100 # 设置队列容量
    threadNamePrefix: "gblfy-signpolicy-asynnotify-" # 设置线程名称前缀
    awaitTerminationSeconds: 60 #  设置线程池等待终止时间()
spring:
  main:
    allow-bean-definition-overriding: true
  1. 编写配置类
@Data
//这个也可以换成在启动类上加:
//@EnableConfigurationProperties(value = {MyThreadPoolConfig.class})
@ConfigurationProperties(prefix = "task.pool")
@Component
public class MyThreadPoolConfig {
    /**
     * 核心线程数
     */
    private Integer corePoolSize;
    /**
     * 最大线程数
     */
    private Integer maxPoolSize;
    /**
     * 临时线程存活时间
     */
    private Integer keepAliveTime;
    /**
     * 设置队列容量
     */
    private Integer queueCapacity;
    /**
     * 设置线程名称前缀
     */
    private String threadNamePrefix;
    /**
     * 设置线程池等待终止时间(秒)
     */
    private Integer awaitTerminationSeconds;

}
  1. 设置线程池参数
import com.sun.istack.internal.logging.Logger;
import com.yepeiqiang.MyThreadFactory.MyThreadPoolConfig;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class NativeThreadPool implements AsyncConfigurer {

    private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(NativeThreadPool.class);
    @Autowired
    private MyThreadPoolConfig config;



    @Override
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(config.getCorePoolSize());
        executor.setMaxPoolSize(config.getMaxPoolSize());
        executor.setQueueCapacity(config.getQueueCapacity());
        executor.setKeepAliveSeconds(config.getKeepAliveTime());
       // executor.setThreadNamePrefix(config.getThreadNamePrefix());
       //我这里修改了一下线程前缀名,待会方便区分
        executor.setThreadNamePrefix("gblfy-signpolicy-asynnotify-asyncConfigurer");
        //设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
        executor.setAwaitTerminationSeconds(config.getAwaitTerminationSeconds());
        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }


    /**
     * 异步任务中的异常处理
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                LOGGER.info("异常:{}",ex);
                LOGGER.info("异常信息:{}",ex.getMessage());
                LOGGER.info("方法名:{}",method.getName());
                LOGGER.info("参数:{}",params);
            }
        };
    }
}

  1. 测试
  • service
@Service
public class TestService3 {


    private static final Logger LOGGER = LoggerFactory.getLogger(TestService3.class);

    @Async
    public void eat(){
        System.out.println("吃饭3");
        LOGGER.info("当前线程名称:{}",Thread.currentThread().getName());
    }
}
@Service
public class TestService4 {


    private static final Logger LOGGER = LoggerFactory.getLogger(TestService4.class);

    @Async
    public void eat(){
        System.out.println("吃饭4");
        LOGGER.info("当前线程名称:{}",Thread.currentThread().getName());
    }
}
  • controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
 
    @Autowired
    private TestService3 testService3;
    @Autowired
    private TestService4 testService4;

    @RequestMapping("/thread")
    public void  test(){
        testService3.eat();
        testService4.eat();
    }
}

输出结果为:

吃饭3
吃饭4
2022-08-30 15:46:17.898  INFO 65336 --- [syncConfigurer1] c.y.testMyThreadPool.TestService3        : 当前线程名称:gblfy-signpolicy-asynnotify-asyncConfigurer1
2022-08-30 15:46:17.899  INFO 65336 --- [syncConfigurer2] c.y.testMyThreadPool.TestService4        : 当前线程名称:gblfy-signpolicy-asynnotify-asyncConfigurer2

一起执行:


        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    private TestService testService;
    @Autowired
    private TestService2 testService2;
    @Autowired
    private TestService3 testService3;
    @Autowired
    private TestService4 testService4;

    @RequestMapping("/thread")
    public void  test(){
        testService.eat();
        testService2.eat();
        testService3.eat();
        testService4.eat();
        new Thread(){
            @Override
            public void run() {
                System.out.println("当前线程名称:"+Thread.currentThread().getName());
            }
        }.start();
    }
}

结果为:

吃饭
吃饭2
吃饭3
吃饭4
2022-08-30 15:48:33.729  INFO 65336 --- [y-asynnotify-10] c.y.testMyThreadPool.TestService2        : 当前线程名称:gblfy-signpolicy-asynnotify-10
2022-08-30 15:48:33.729  INFO 65336 --- [yncConfigurer10] c.y.testMyThreadPool.TestService4        : 当前线程名称:gblfy-signpolicy-asynnotify-asyncConfigurer10
2022-08-30 15:48:33.729  INFO 65336 --- [syncConfigurer9] c.y.testMyThreadPool.TestService3        : 当前线程名称:gblfy-signpolicy-asynnotify-asyncConfigurer9
2022-08-30 15:48:33.729  INFO 65336 --- [cy-asynnotify-9] c.y.testMyThreadPool.TestService         : 当前线程名称:gblfy-signpolicy-asynnotify-9
当前线程名称:Thread-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值