标签:
ThreadPoolExecutor提供了四种构造方法:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler. ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory. ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) Creates a new ThreadPoolExecutor with the given initial parameters and default rejected execution handler. ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) Creates a new ThreadPoolExecutor with the given initial parameters.
当然也可以通过Executors类构建,不过需要类型强转以及手动去配置一些属性。
对于构造函数中的参数:
corePoolSize:正常运行时线程量。
maximumPoolSize:最大容纳的线程数量。
keepAliveTime:线程的生命时长
unit:与keepAliveTime对应代表时间的单位
workQueue:队列
handler:提交线程数量大于maximumPoolSize时的处理器
threadFactory:线程创建工厂
说明:
如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列。如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。也就是:处理任务的优先级为:核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。当线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。
handler有四种处理方式:
static class ThreadPoolExecutor.AbortPolicy A handler for rejected tasks that throws a RejectedExecutionException. static class ThreadPoolExecutor.CallerRunsPolicy A handler for rejected tasks that runs the rejected task directly in the calling thread of the execute method, unless the executor has been shut down, in which case the task is discarded. static class ThreadPoolExecutor.DiscardOldestPolicy A handler for rejected tasks that discards the oldest unhandled request and then retries execute, unless the executor is shut down, in which case the task is discarded. static class ThreadPoolExecutor.DiscardPolicy A handler for rejected tasks that silently discards the rejected task.
AbortPolicy:抛出异常给调用者
CallerRunsPolicy:在调用者所在线程执行、
DiscardOldestPolicy:抛弃等待队列中等待最长的那个任务,并把这个任务加入到队列
DiscardPolicy:抛弃任务
部分方法说明:
execute:执行任务
getCorePoolSize:获取普通运行时线程数量上限
getPoolSize:获取当前线程池数量
getQueue:获取等待队列
getActiveCount:获取正在执行的线程数量(估计值)
标签:
原文地址:http://my.oschina.net/shyloveliyi/blog/480500