代码改变世界

ThreadPoolTaskExecutor和ThreadPoolExecutor区别

2023-04-15 21:04  youxin  阅读(178)  评论(0编辑  收藏  举报

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

 

方式1【推荐】: 使用 CountDownLatch

public class TestThreadPool {

    public static void main(String[] args) throws InterruptedException {

        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setThreadNamePrefix("xxxx-");
        threadPoolTaskExecutor.setCorePoolSize(1);
        threadPoolTaskExecutor.setMaxPoolSize(5);
        threadPoolTaskExecutor.setQueueCapacity(5);
        threadPoolTaskExecutor.setKeepAliveSeconds(300);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                System.out.println("丢弃");
            }
        });
        threadPoolTaskExecutor.initialize();

        int taskNum = 10;
        CountDownLatch latch =  new CountDownLatch(taskNum);

        for (int i=0; i < taskNum; i++) {
            final int taskId = i;
            System.out.println("-- submit task " + taskId);
            threadPoolTaskExecutor.execute(() -> {
                try {
                    System.out.printf("task: %s, thread: %s, start at %d\n", taskId, Thread.currentThread().getName(), System.currentTimeMillis()/1000);
                    Thread.sleep(2_000);
                    System.out.printf("task: %s, thread: %s, end at %d\n", taskId,  Thread.currentThread().getName(), System.currentTimeMillis()/1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            });
        }

        latch.await();
        threadPoolTaskExecutor.shutdown();
    }
}

 

方式2: 使用 Future
ThreadPoolTaskExecutor 线程池等待所有任务完成的几种方式
参考URL: https://www.letianbiji.com/spring/spring-ThreadPoolTaskExecutor-wait-tasks-done.html
建议参考原文。

方式3: setWaitForTasksToCompleteOnShutdown(true)
ThreadPoolTaskExecutor 线程池等待所有任务完成的几种方式
参考URL: https://www.letianbiji.com/spring/spring-ThreadPoolTaskExecutor-wait-tasks-done.html

建议参考原文。
原文链接:https://blog.csdn.net/inthat/article/details/109596279

 

 

 

ThreadPoolTaskExecutor 线程池等待所有任务完成的几种方式
ThreadPoolTaskExecutor 线程池等待所有任务完成的几种方式
参考URL: https://www.letianbiji.com/spring/spring-ThreadPoolTaskExecutor-wait-tasks-done.html

建议参考原文。
————————————————
原文链接:https://blog.csdn.net/inthat/article/details/109596279

 

 

 

 https://zhuanlan.zhihu.com/p/346086161

 

https://zhuanlan.zhihu.com/p/257135280