ThreadPoolTaskExecutor和ThreadPoolExecutor区别

发布时间 2023-04-15 21:11:04作者: youxin

ThreadPoolExecutor是Java原生的线程池类,而ThreadPoolTaskExecutor是Spring推出的线程池工具

 

 

一、从核心参数看两者关系

 

ThreadPoolExecutor(java.util.concurrent)

 

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.acc = System.getSecurityManager() == null ?
        null :
    AccessController.getContext();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent)

public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements AsyncListenableTaskExecutor, SchedulingTaskExecutor {
    private final Object poolSizeMonitor = new Object();
    private int corePoolSize = 1;
    private int maxPoolSize = 2147483647;
    private int keepAliveSeconds = 60;
    private int queueCapacity = 2147483647;
    private boolean allowCoreThreadTimeOut = false;
    @Nullable
    private TaskDecorator taskDecorator;
    @Nullable
    private ThreadPoolExecutor threadPoolExecutor;
    private final Map<Runnable, Object> decoratedTaskMap;

    public ThreadPoolTaskExecutor() {
        this.decoratedTaskMap = new ConcurrentReferenceHashMap(16, ReferenceType.WEAK);
    }
}

ThreadPoolTaskExecutor的核心参数共有四个,分别是corePoolSize,maxPoolSize,keepAliveSeconds以及queueCapacity。

corePoolSize:核心线程数量(对应ThreadPoolExecutor的corePoolSize)
maxPoolSize:最大线程数量(对应ThreadPoolExecutor的maximumPoolSize)
keepAliveSeconds:线程池维护线程所允许的空闲时间(对应ThreadPoolExecutor的keepAliveTime)
queueCapacity:工作队列容量(对应ThreadPoolExecutor的workQueue的容量)
从ThreadPoolTaskExecutor的唯一带参构造方法可以看出,似乎并没有对上述四个核心参数做自定义初始化的工作,实际上,ThreadPoolTaskExecutor在底层依然依赖ThreadPoolExecutor本身,也就是说该工具更关注于扩展的内容,执行任务依然交由ThreadPoolExecutor去处理。

二、底层原生线程池依赖解析
从上述代码中可以看到,ThreadPoolTaskExecutor继承了ExecutorConfigurationSupport类,该类不仅体现了Spring自身的设计思想,也是ThreadPoolTaskExecutor底层调用ThreadPoolExecutor的具体实现。
————————————————
原文链接:https://blog.csdn.net/weixin_50604409/article/details/119224004