线程池

thread.png
pool.png
poolParams.png
 /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory and rejected execution handler.
     * It may be more convenient to use one of the {@link Executors} factory
     * methods instead of this general purpose constructor.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @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.
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue} is null
     */

如果线程数小于corePoolSize则直接创建新线程来处理任务,即使线程中的其他线程是空闲的;
如果线程池中的线程数量
大于等于corePoolSize且小于*maximumPoolSize时,则只有当workQueue满的时候才创建新线程处理任务;
如果设置的corePoolSizemaximumPoolSize相同的话,那么线程池的大小是固定的,如果有新任务提交,workQueue还没满就把请求放入workQueue中等待空闲线程取出任务处理;
如果运行任务大于maximumPoolSize的时候,如果workQueue也满了则用拒绝策略

  • workQueue: 处理任务有三种方式:
  1. 直接切换(SynchronousBlockingQueue) 2. 有界队列(ArrayBlockingQueue) 3.无界队列(LinkedBlockingQueue)
exe.png

拒绝策略:

  1. 直接抛出异常(默认)
  2. 用调用者所在的线程来执行任务
    3.丢弃队列中最靠前的任务来执行当前任务
  3. 直接丢弃此任务
policy.png
state.png
  • Running状态:能接收新提交的任务并且也能处理阻塞队列中的任务
  • Shutdown: 不能接收新提交的任务,但是可以处理阻塞队列中已经保存的任务
  • STOP: 不能接收新提交的任务,也不处理队列中的任务
method.png
monitor.png
diagram.png
interface.png
config.png
juc.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容