ThreadPoolExecutor各参数之意义

Java 为我们提供了操作线程池的API: ThreadPoolExecutor ,该类实现了 ExecutorService 接口

JDK 中相关的线程池的类都实现了该接口。

创建一个线程池可以通过 ThreadPoolExecutor 类来实现:

ThreadPoolExecutor executor= new ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long 
keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue);
 
//执行任务
executor.execute(runnable);
下面是官方对 ThreadPoolExecutor 的参数说明:

Parameters:
    corePoolSize - the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
    maximumPoolSize - the maximum number of threads to allow in the pool
    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.
    unit - the time unit for the keepAliveTime argument
    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.
下面对各个参数进行个解释:

corePoolSize 核心线程数,核心线程会一直存活,即使没有任务需要处理。当线程数小于核心线程数时,即使现有的线程空闲,线程池也会优先创建新线程来处理任务,而不是直接交给现有的线程处理。核心线程在allowCoreThreadTimeout被设置为true时会超时退出,默认值为false不会退出。
maxPoolSize 线程池允许最大的线程数量(包括核心线程和非核心线程)。
keepAliveTime 当线程空闲时间达到 keepAliveTime,该线程会退出,直到线程数量等于 corePoolSize。如果allowCoreThreadTimeout 设置为 true,则所有线程均会退出直到线程数量为0。
allowCoreThreadTimeout 是否允许核心线程空闲keepAliveTime退出,默认值为false。
workQueue 任务队列。一般使用的是ArrayBlockingQueue<Runnable>。executor.execute(runnable) 提交的 task都 会放到workQueue。

     当我们通过execute(runnable)向ThreadPoolExecutor提交任务时,首先都是将其任务提交到workQueue 任务队列中,然后核心线程和非核心线程再从该任务队列取任务出来执行。如果提交任务后,导致workQueue 任务队列被塞满,系统会尝试启动更非核心线程(最大数为maxPoolSize-corePoolSize)来执行任务。如果提交任务时,workQueue 任务队列已经被塞满,会抛出RejectedExecutionException.不过在构造ThreadPoolExecutor时通过指定个性化的RejectedExecutionHandler来做个性化处理。另外,当非核心线程没有任务需要执行,空闲时间达到 keepAliveTime时,线程会退出消亡。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值