记事本
1. 编程
1.1 Java
1.1.1 线程池
线程池 7大配置
/**
* 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
* @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}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler){
}
- corePoolSise: 要保留在池中的线程数,即使它们处于空闲状态,除非 allowCoreThreadTimeOut 已设置
- maximumPoolSize 池中允许的最大线程数
- keepAliveTime 当线程数大于核心数时,这是多余的空闲线程在终止之前等待新任务的最长时间。
- unit 参数的时间 keepAliveTime 单位
- workQueue 用于在执行任务之前保留任务的队列。此队列将仅 Runnable 保存该方法提交 execute 的任务
- threadFactory 执行器创建新线程时使用的工厂
- handler 由于达到线程边界和队列容量而被阻止执行时要使用的处理程序
线程池执行的流程
- 线程池创建,准备好core数量的核心,准备接受任务
- 新的任务进来,用core准备好的空闲线程执行
1)core满了,就将再进来的任务放入到阻塞队列中,空闲的core就会自己去阻塞队列获取任务并执行
2)阻塞队列满了,就直接开新线程执行,最大只能开到指定的数量
3)max 都执行好了 max-core数量空闲的线程会在keepAliveTime指定的时间后自动销毁。最终保持到core大小
3)如果线程数开到了max的数量,还有新任务进来,就会使用reject指定的拒绝策略进行处理 - 所有线程穿件都是由指定的factory创建的