Why do you need on a thread pool thread pool?
A thread is the basic unit of processor scheduling. We will independently create a thread for each request, and the operating system creates a thread switching thread state, the end of the thread to be using the CPU scheduling.
Achieve thread pool:
ScheduledThreadPoolExecutor
ThreadPoolExecutor
ForkJoin Pool
The logical structure of the thread pool
创建线程池的构造函数
public ThreadPoolExecutor(
int corePoolSize, #核心线程数
int maxinmumPoolSize, #线程总数 非核心数=总数-核心数
long keepAliveTime, #当前线程数大于核心线程数时 线程的等待新任务的等待时间(核心线程也会面临死亡)
TimeUnit unit, #时间单位
BlockingQueue<Runnable> workQueue #任务队列
RejectedExecutionHandler #(选填) 拒绝处理器
)
poolExecutor 线程池对象
submit(任务) execute(任务) 将任务送入到任务队列 任务对象要实现Runnable接口或者Callable接口
核心:
当前运行线程数 小于corePoolSize 任务直接交给核心线程进行执行(通过线程调度执行任务)
当前运行线程数 大于或等于 corePoolSize 任务且满足队列规则 任务将进入任务队列进行等待
当前运行线程数 大于或等于 corePoolSize 任务且不满足队列规则 任务进入非核心线程(这类线程有存活时间,不一定会执行成功)
任务队列(实现BlockingQueue接口)
SyschronousQueue:每一次add()插入 必须要等待相对删除/读取操作
ArrayBlockingQueue:数组的方式,大小创建后不能改变大小,具有阻塞特性。
LinkedBlockingQueue:无限容量 基于链表的形式
LinkedBlockingDeque :无限双端链表队列,可以从两头进行元素的读/取操作
PriorityBlockingQueue:按照优先级进行内部元素排序的无限队列。
LinkedTransferQueue:无限队列,先进先出,具有阻塞特性。
#阻塞特性:当队列满了,便会阻塞等待,直到有元素出队,后续的元素才可以被加入队列。
关于拒绝处理器
适用:那些既不能进入核心线程、等待队列,也无法创建新的线程执行(即非核心线程),或者线程异常等。
CallerRunsPolicy:直接运行该任务的run方法,但不是在线程池内部
AbortPolicy:RejectedExecutionException异常抛出(默认)
DiscardPolicy:不会做任何处理
DiscardOldestPolicy:检查等待队列 强行取出队列头部任务 进行执行