使用线程池可以对线程进行统一的分配、监控和调优,降低系统资源消耗,提升系统稳定性。
1. 使用线程池的好处
- 降低资源的消耗: 线程池通过重复利用线程中已存在的线程,从而降低了创建线程和销毁线程所造成的资源消耗。
- **提升响应速度: ** 当任务到达时,任务不需要等待创建线程,而直接使用线程池中已存在的线程就可以立即执行。
- **提高线程的可管理性: ** 使用线程池,可以对池中的线程进行统一的调度、监控,从而提升系统的稳定性。
2. 线程池工作原理
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);
}
线程池处理流程如下:
- 线程池判断核心线程池中的线程是否都在执行任务,如果不是,则创建一个新的工作线程来执行任务。如果核心线程里的线程都在执行任务,则进入下一个流程;
- 线程池判断工作队列是否已满,如果工作队列未满,则将任务添加到工作队列中,如果队列已满,则执行下一个流程;
- 线程池判断线程池是否已满,如果未满,则创建一个新的工作线程来执行任务,如果已满,则将任务交给饱和策略来处理任务;