自定义线程池 线程池参数详解

private static int corePoolSize = 20;
private static int maxPoolSize = 100;
private static int keepAliveTime = 0;
private static TimeUnit timeUnit = TimeUnit.MINUTES;
private static BlockingQueue blockingQueue = new ArrayBlockingQueue<>(9999);
private static RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

private static ThreadPoolExecutor pool = 
    new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, blockingQueue, handler);
  • corePoolSize: 线程池的核心线程数(公司骨干成员)
  • maxPoolSize: 线程大容量(公司最多能容纳这些人)
  • keepAliveTime: 非核心线程存活时间
  • timeUnit: 时间单位(秒还是分)
  • blockingQueue: 阻塞队列 , 当线程数达到核心线程数时,任务就会在阻塞队列中等待,若等待的任务数大于指定队列的大小,则开启非核心线程进行执行任务, 最maxPoolSize个
  • RejectedExecutionHandler: 拒绝策略 当线程数量达到非核心线程数, 并且队列中的等待的任务也满了, 那么则执行拒绝策略

其他决绝策略, 点击查看 

项目统一用一个线程池

public final class ThreadPoolFactory {

    private static volatile ThreadPoolExecutor threadPoolExecutor = null;

    private static final int CORE_POOL_SIZE = 0;
    private static final int MAX_MUM_POOL_SIZE = 1000;
    private static final long KEEP_ALIVE_TIME = 2;
    private static final TimeUnit UNIT = TimeUnit.MINUTES;
    private static final int CAPACITY = 20;
    private static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

    private ThreadPoolFactory() {
    }

    public static ThreadPoolExecutor getInstance() {
        if (threadPoolExecutor == null) {
            synchronized (ThreadPoolFactory.class) {
                if (threadPoolExecutor == null) {
                    threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_MUM_POOL_SIZE, KEEP_ALIVE_TIME, UNIT, new ArrayBlockingQueue<>(CAPACITY), HANDLER);
                }
            }
        }
        return threadPoolExecutor;
    }
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值