您的位置:首页 > 编程语言 > Java开发

Java中的线程池

2016-03-31 22:55 471 查看
线程池对应的类为java.util.concurrent.ThreadPoolExecutor
构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)

*@param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* 核心线程数,就是即使空闲也保持存活,将允许核心线程退出设置为true
* @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 handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* 当线程池中的线程数量等于最大线程数量,且任务队列已满,则由handle分配处理策略

通过ThreadPoolExecutor类的方法public void execute(Runnable command)将线程任务添加到线程池的步骤:
(1)如果线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态也会创建新的线程来处理被添加的任务
(2)如果线程池中的数量等于corePoolSize且都不空闲,但是缓冲队列未满(缓冲队列有任务证明线程池中至少有corePoolSize个不空闲线程),则将任务添加到缓冲队列中
(3)如果线程池中的数量等于或大于corePoolSize小于maximumPoolSize ,缓冲队列满,则创建新线程处理任务
(4)如果线程池中的数量等于maximumPoolSize ,且缓冲队列满,则采用handler所指定的策略来处理任务
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: