Java中的线程池

来源:互联网 发布:msp430用什么软件编程 编辑:程序博客网 时间:2024/06/05 23:38
线程池对应的类为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所指定的策略来处理任务


0 0
原创粉丝点击