JAVA 线程池分析: ThreadPoolExecutor

ThreadPoolExecutor 构建

构造函数

// 带有默认拒绝策略的构造函数
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

// 完整的构造函数
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {}

参数描述

  1. corePoolSize 线程池中的线程数量, 最少数量
  2. maximumPoolSize 最大线程数量
  3. keepAliveTime 线程最大的等待时间
  4. unit 上面时间的单位
  5. workQueue 使用的缓冲队列
  6. threadFactory 线程队列
  7. handler 线程满了, 拒绝处理方案

参数5. 缓冲队列说明

线程队列 实现 BlockingQueue, 分为三大类

1: SynchronousQueue (直接移交)同步队列, 只有一个元素, 删除一个, 才能继续添加
2: LinkedBlockingQueue (无线队列)链表队列, 先进先出. 多线程预测性比较差
3: ArrayBlockingQueue (有界队列)数组队列, 先进先出, 大小创建之后无法改变.

参数7. 拒绝策略

实现 接口: RejectedExecutionHandler

  1. AbortPolicy : 抛出异常
	/**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     */
  1. DiscardPolicy : 丢弃拒绝任务
/**
     * A handler for rejected tasks that silently discards the
     * rejected task.
     */
  1. DiscardOldestPolicy : 丢弃最老的(队列最先进来的)未处理程序
/**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     */
  1. CallerRunsPolicy : 直接执行被拒绝的 Runnable方法, 在main(主线程)
 /**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值