一日一技 (3) 如何创建线程池ThreadPoolExecutor

阿里开发规范不要显示创建线程池,也不要用excutors静态方法创建线程池,而是用ThreadPoolExecutor。

使用示例:

static ThreadFactory myThreadFactory = new
ThreadFactory() {
    @Override
    public Thread newThread(Runnable runnable) {
        return new Thread(runnable);
    }
};

public static ExecutorService pool = new ThreadPoolExecutor(1, 12,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>(1024), myThreadFactory, new ThreadPoolExecutor.AbortPolicy());

ThreadPoolExecutor构造方法中各个参数的含义:

corePoolSize:线程池拥有的线程数量,不管空闲不空闲一直都在的。
maximumPoolSize: 线程池中允许的最大线程数量。
keepAliveTime:当线程池中线程最大的闲置时间,到了限制时间会销毁非核心线程。
unit:闲置时间单位,秒,分,时。
workQueue:任务无法获得线程进行处理时进入该队列等待。
threadFactory:线程工厂,具体的创建线程的方法,开放创建线程时操作。
handler:当任务无法提交,等待队列也满时,对任务的处理方法。

源码注释:

/**
 * Creates a new {@code ThreadPoolExecutor} with the given initial
 * parameters.
 * @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.
 * @param threadFactory the factory to use when the executor
 *        creates a new thread
 * @param handler the handler to use when execution is blocked
 *        because the thread bounds and queue capacities are reached
 * @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}
 *         or {@code threadFactory} or {@code handler} is null
 */
  • 5
    点赞
  • 0
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页

打赏

兴趣使然的程序猿

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付 19.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值