在Java中,如果每个请求到达就创建一个新线程,创建和销毁线程花费的时间和消耗的系统 资源都相当大,甚至可能要比在处理实际的用户请求的时间和资源要多的多。 如果在一个 Jvm 里创建太多的线程,可能会使系统由于过度消耗内存或“切换过度”而导致系 统资源不足 为了解决这个问题,就有了线程池的概念,线程池的核心逻辑是提前创建好若干个线程放在一 个容器中。如果有任务需要处理,则将任务直接分配给线程池中的线程来执行就行,任务处 理完以后这个线程不会被销毁,而是等待后续分配任务。同时通过线程池来重复管理线程还 可以避免创建大量线程增加开销。
合理的使用线程池,可以带来一些好处
public class ExecutorsDemo implements Runnable{
public static void main(String[] args) {
// 没有线程池时创建线程执行
Thread t1 = new Thread(new ExecutorsDemo());
t1.start();
// 使用线程池创建固定大小为3的线程池,把任务交给线程池执行
ExecutorService executorService = Executors.newFixedThreadPool(3);
for(int i=0;i<10;i++) {
executorService.execute(new ExecutorsDemo());
}
executorService.shutdown();
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
上述四种线程池都是基于ThreadPoolExecutor类来创建的,他们存在的意义是在特定场景使用方便,针对特殊场景我们也可以基于ThreadPoolExecutor手动定制符合我们需求的线程池
我们先看下newFixedThreadPool的源码:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
ThreadpoolExecutor有多个重载的构造方法,我们可以基于它最完整的构造方法来分析 先来解释一下每个参数的作用
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
corePoolSize:核心线程池的大小。在创建了线程池之后,默认情况下,线程池中线程数为0,当有任务到来才创建线程去执行任务。当线程池中线程数量达到核心线程池的数量后,后续线程池至少会存在核心线程池数量大小的线程
maximumPoolSize:池中允许的最大线程数,这个参数表示了线程池中最多能创建的线程数量。
keepAliveTime:只有当线程池中的线程数大于corePoolSize时,这个参数才会起作用。当线程数大于corePoolSize时,空闲的线程等待keepAliveTime时间后没有被调用就会执行结束
unit:keepAliveTime 的时间单位
workQueue:阻塞队列,当线程池任务大于corePoolSize,多余的任务会被加入阻塞队列等待被调用
threadFactory:执行程序创建新线程时使用的工厂
handler:拒绝策略,当任务数量大于maximumPoolSize+workQueue队列大小时,采用什么方式拒绝
线程池执行流程如下图所示((FixedThreadPool):
即:任务进来->使用核心线程执行->核心线程满了扔到阻塞队列->阻塞队列满了再创建非核心线程->还是满了->根据拒绝策略执行处理
那么为什么核心线程满了是先给阻塞队列,而不是直接创建非核心线程处理呢?
因为当前核心线程有能力处理多余的任务,后续进来的任务由当前核心线程是有能力处理完的。只有当任务足够多时才需要创建非核心线程来共同处理
源码解析:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
// 当当前线程池线程数量小于核心线程数
if (workerCountOf(c) < corePoolSize) {
// 初始时总线程数量为0,此时创建一个work线程来执行进来的任务
if (addWorker(command, true))
return;
c = ctl.get();
}
// 线程池线程数量大于核心线程数了,
// 那么把任务扔到阻塞队列workQueue中
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);
}
// 上述都没有返回,则说明阻塞队列也满了,再次创建work线程来执行任务
else if (!addWorker(command, false))
// addWorker创建失败了,那么执行拒绝策略
reject(command);
// 流程结束,可以看到流程还是非常清晰的
}
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
// 状态大于SHUTDOWN并且并且 rs不等于 SHUTDOWN且 firstTask不等于空并且阻塞队列满了,那么不能增加work了,返回false
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
// 根据是要创建核心线程还是非核心线程来判断当前线程数量是否饱和,饱和了则返回false
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
// 通过cas把work工作线程+1, return ctl.compareAndSet(expect, expect + 1);
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
// 以上代码只是检测是否可以创建work,下面是创建work的流程
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
// 创建一个work,work是什么呢?首先他的构造函数接收了我们传进来的Runable
w = new Worker(firstTask);
// 从worker里面拿出了一个线程
final Thread t = w.thread;
if (t != null) {
// 使用重入锁保证线程安全
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
// 满足要求,则添加状态设置为true
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
// 如果添加成功,则启动线程
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
Wocker类:
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
/**
* This class will never be serialized, but we provide a
* serialVersionUID to suppress a javac warning.
*/
private static final long serialVersionUID = 6138294804551838833L;
/** Thread this worker is running in. Null if factory fails. */
final Thread thread;
/** Initial task to run. Possibly null. */
// 第一次创建work时传进来的对象
Runnable firstTask;
/** Per-thread task counter */
volatile long completedTasks;
/**
* Creates with given first task and thread from ThreadFactory.
* @param firstTask the first task (null if none)
*/
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
// 根据Worker创建出一个线程,即thread启动后会调用当前Worker的run方法
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
// Lock methods
//
// The value 0 represents the unlocked state.
// The value 1 represents the locked state.
protected boolean isHeldExclusively() {
return getState() != 0;
}
protected boolean tryAcquire(int unused) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
public void lock() {
acquire(1); }
public boolean tryLock() {
return tryAcquire(1); }
public void unlock() {
release(1); }
public boolean isLocked() {
return isHeldExclusively(); }
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
}
Worker类详解:
1、Worker继承了Runable,在构造函数中根据当前Worker创建了一个线程thread,保存到了当前成员变量,在创建Worker时会启动线程,调用当前run(),run()里面调用了runWorker()
2、Worker类成员变量firstTask,保存创建线程时传进来的任务,在thread启动后也会执行firstTask的run()
3、runWorker方法是Worker类启动后真正执行的方法。内部通过while循环不停的去阻塞队列take数据,即只要while条件满足则Worker线程不会被停止,这就是核心线程一直保留在线程池的方式。
4、当线程数量大于核心线程时,当有线程空闲一段时间不满足while条件时即线程会执行结束,这就是线程回收的方式
runWorker方法:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 核心代码1,关于当前线程是否执行结束,当getTask() != null时结束
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
// 核心代码2:执行创建Worker对象时传进来的第一个任务
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
getTask方法:
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
/**
* 核心代码
* 1、poll会等待keepAliveTime时间后返回null,即当调用poll没有获得数据时结束了当前Worker
* 2、take会持续阻塞
*/
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
根据上述源码中的核心代码,我们还是可以大致了解线程池的工作流程和原理的。至于其中复制场景的考虑以及线程安全等各种考虑,还是比较复杂。不得不说我们j.u.c并发包的开发大师Doug Lea还是非常厉害的