Java线程池
涉及多线程编程,我想不得不提及的就是线程池,尽管市面上关于线程池的文章很多,但是作为一个进阶的程序猿,亲自阅读源码,了解工作流程是一个很有必要的
线程池优势
为什么要用线程池,无非就是线程池有不可替代的优势
- 控制线程避免过度的创建和销毁所带来的性能隐患
- 控制线程并发数量,避免高并发所带来的cpu资源争夺导致的资源紧张(cpu时间分片)
ThreadPoolExecutor
这个是java种使用线程池的核心类,参数说明
- corePoolSize:核心线程数,一般配置cpu核数+1,除非参数allowCoreThreadTimeOut被设置成true,那么核心线程是不会被回收的,即使是空闲状态
- maximumPoolSize:线程池中能拥有最多线程数,一般配置cpu*2+1
- workQueue:用于缓存任务的阻塞队列
- keepAliveTime:表示空闲线程的存活时间
- TimeUnitunit:表示keepAliveTime的单位。
- ThreadFactory:用来创建线程使用
- RejectedExecutionHandler:表示当workQueue已满,且池中的线程数达到maximumPoolSize时,线程池拒绝添加新任务时采取的策略。
工作流程
- 核心线程数未满,直接创建新的核心线程来执行任务,若有空闲线程,复用空闲线程
- 核心线程数已满,要执行的任务加入堵塞队列
- 核心线程数已满,堵塞队列已满,创建非核心线程来执行任务(非时序关联的流程,非核心线程若空闲,并且到达存活时间,会被回收),若有空闲线程,可复用
- 核心线程已满,堵塞队列已满,非核心线程已满,任务会被拒绝执行,调用RejectedExecutionHandler
工作流程源码分析
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
//上面的英文表达的就是线程池的工作流程
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
//若工作中的线程数小于核心线程,直接执行
if (addWorker(command, true))
return;
c = ctl.get();
}
//核心已满,加入堵塞队列
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
//尝试着将任务加入非核心线程,若加入失败,拒绝执行
else if (!addWorker(command, false))
reject(command);
}
总结
若只是使用线程池,上面的知识点足够用了,下一篇,深度进入源码,剖析线程池的原理