Java 线程池的ThreadPoolExecutor之参数解释

Java线程池通过ThreadPoolExecutor实现,提供统一管理和复用线程的能力,避免频繁创建销毁线程的开销。核心参数包括:corePoolSize(核心线程数)、maximumPoolSize(最大线程数)、keepAliveTime(非核心线程空闲超时时间)和workQueue(任务队列)。线程池还包括ThreadFactory用于创建新线程,以及拒绝策略如CallerRunsPolicy、AbortPolicy等应对任务提交超出限制的情况。
摘要由CSDN通过智能技术生成

我们单纯的去创建一个线程可以用new Thread

但是这个有弊端,就是再高并发的情况,new Thread 每次都要去创建一个线程,用完需要摧毁它,这样非常的消耗时间。线程多的情况下没办法统一管理。

如何统一管理线程和复用已经创建的线程呢?

就有了线程池这个概念。线程池的工作流程:

Java 常规的线程池有四种:newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor,这四种都是Executors提供的。都是通过ThreadPoolExecutor实现的。先介绍下ThreadPoolExecutor。

/**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory and rejected execution handler.
     * It may be more convenient to use one of the {@link Executors} factory
     * methods instead of this general purpose constructor.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值