ThreadPoolExecutor 源码讲解

1 背景

主要的应用场景,作者主要遇到过,需要的场景主要有如下两种场景

  •   单线程处理速度慢
  •   同步处理速度慢,想同步转异步

2 ThreadPoolExecutor简介

TheadPoolExecutor 是Java提供的线程池类,本人总结的技术优势如下

  • 支持多线程运行
  •  线程复用
  • 任务存储队列
  • 支持多种任务拒绝策略
  • 自定义运行线程数 以及存储队列长度

3 创建ThreadPoolExecutor

3.1 简介

有4种方式构造ThreadPoolExecutor, 本质上就一种,另外三种只不过都是带默认值

3.2 不带默认参数的构造器

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) 

  3.2.1 corePoolSize

the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set   核心线程数


 3.2.2  maximumPoolSize

 the maximum number of threads to allow in the pool  最大线程数

 3.2.3  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.   空闲线程的存活时间

 3.2.4  TimeUnit

 the time unit for the keepAliveTime argument 时间单位

 3.2.5  workQueue

the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method,用于存放任务的队列

 3.2.6  threadFactory

 the factory to use when the executor creates a new thread 线程工厂,用于创建线程

 3.2.7  RejectedExecutionHandler

 the handler to use when execution is blocked because the thread bounds and queue capacities are reached 处理被拒绝的任务

4 创建一个任务并运行

 

  4.1   实现Runnable 接口

   4.2  调用execute方法

   

 public void execute(Runnable command)

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值