9.异步与线程池

一、课件

二、线程池

2.1 线程池的七大参数

/**

* Creates a new {@code ThreadPoolExecutor} with the given initial

* parameters.

*

* @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.

* @param threadFactory the factory to use when the executor

* creates a new thread

* @param handler the handler to use when execution is blocked

* because the thread bounds and queue capacities are reached

  1. corePoolSize: 池中一直保持的线程的数量,即使线程空闲。除非设置了 allowCoreThreadTimeOut
  2. maximumPoolSize: 池中允许的最大的线程数
  3. keepAliveTime: 当线程数大于核心线程数的时候,超出核心线程数的线程在最大多长时间没有接到新任务就会终止释放 ,最终线程池维持在 corePoolSize 大小
  4. unit: 时间单位
  5. workQueue: 阻塞队列,用来存储等待执行的任务,如果当前对线程的需求超过了 corePoolSize大小, 就 会放在这里 等待空闲线程执行.
  6. threadFactory:创建线程的工厂,比如指定线程名等
  7. handler:拒绝策略,如果线程满了,线程池就会使用拒绝策略。

2.2 运行流程

1、线程池创建,准备好 core 数量的核心线程,准备接受任务

2、新的任务进来,用 core 准备好的空闲线程执行。

(1) 、core 满了,就将再进来的任务放入阻塞队列中。空闲的 core 就会自己去阻塞队列获取任务执行

(2) 、阻塞队列满了,就直接开新线程执行,最大只能开到 max 指定的数量

(3) 、max 都执行好了。Max-core 数量空闲的线程会在 keepAliveTime 指定的时间后自动销毁。最终保持到core 大小

(4) 、如果线程数开到了 max 的数量,还有新任务进来,就会使用 reject 指定的拒绝策略进行处理

3、所有的线程创建都是由指定的 factory 创建的。

面试:

一个线程池 core 7; ; max 20 ,queue :50 ,100 并发进来怎么分配的;

先有 7 个能直接得到执行,接下来 50 个进入队列排队,在多开 13 个继续执行。现在 70 个

被安排上了。剩下 30 个使用拒绝策略。

posted @ 2022-03-17 10:44  随遇而安==  阅读(73)  评论(0编辑  收藏  举报