介绍线程池的执行流程,及源码分析
线程池接收任务:
1.先创建核心work,执行任务,核心work创建满了,再来新的任务,没有空闲的核心work,
2.就将任务放进队列,队列添加满了,
3.就创建非核心work,此时,非核心work和核心work一起执行队列中的任务,当核心、非核心work、队列都满了,再添加任务,就执行拒绝策略
注1:一个线程池创建的work数量是有限的,当work达到ctl最大值即563870912,此线程池就拒绝接收任务,每次创建一个work,不论是核心还是非核心的,ctl值都会加1,当ctl值从-563870912加到0时就不接收任务了。
if (! isRunning(recheck) && remove(command)) reject(command)
这个判断中 isRunning(recheck)就是判断ctl < SHUTDOWN,( SHUTDOWN=0)
注2:如果核心work=0,任务直接进入队列,创建一个非核心work,从队列中取任务
源码分析:
测试代码
import java.util.concurrent.*;
/**
* @Author wfl 2022/1/11
* 功能
*
* RUNNING
* 1110 0000 0000 0000 0000 0000 0000 0000
*
* SHUTDOWN
* 0000
*
* STOP
* 0010 0000 0000 0000 0000 0000 0000 0000
*
* TIDYING
* 0100 0000 0000 0000 0000 0000 0000 0000
*
* TERMINATED
* 0110 0000 0000 0000 0000 0000 0000 0000
*
* 0001 1111 1111 1111 1111 1111 1111 1111
* 1110 0000 0000 0000 0000 0000 0000 0011
*/
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService service = new ThreadPoolExecutor(1,2,60, TimeUnit.SECONDS,new LinkedBlockingDeque<>());
for (int i = 0; i < 5; i++) {
int finalI = i;
Thread thread = new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"---"+finalI);
});
try {
service.execute(thread);
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
int finalI = i;
Thread thread = new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"---"+finalI);
});
try {
service.execute(thread);
} catch (Exception e) {
e.printStackTrace();
}
}
// service.shutdown();
}
}
当执行service.execute(thread);会进入添加任务
如果设置了核心线程数corePoolSize的值,并且大于0,就会进入添加work方法,注意这里的ctl的初始值是-536870912,每次添加一个work,不管是核心还是非核心的,都会加1,当ctl=0时就不接收任务了,就会执行
if (! isRunning(recheck) && remove(command)) reject(command);
这里面的reject(command)
//java.util.concurrent.ThreadPoolExecutor#execute
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
// work的数量与corePoolSize比较
if (workerCountOf(c) < corePoolSize) {
// 首先创建核心work,将command放入,启动work线程,循环执行任务
if (addWorker(command, true))
return;
c = ctl.get();
}
// 核心work创建够了,就判断线程池是运行状态,存入队列成功
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
// 只有核心work。corePoolSize=0时,第一次才会进入这里,先创建一个非核心的work,任务=null,他就会从队列中取
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 核心work创建够了,队列也满了,尝试创建非核心work,创建成功,就可以执行任务
else if (!addWorker(command, false))
// 创建不成功,执行拒绝策略
reject(command);
}
work是线程池的一个内部类,任务添加成功会执行t.start();调用work类中run方法
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
// 从线程池工厂创建一个新线程
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
下面看看runWork(this)方法
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 这里会循环执行,getTask()就是从队列中取任务,当work数量大于核心work数量即,有非核心work时,
//这里getTask()取出的就是null,就会跳出循环,执行最后的退出方法 processWorkerExit(w, completedAbruptly);移除这个work
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 {
//执行任务时,实际是对象调用run方法。
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,下次循环重新获取。
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
//执行退出方法,移除work
processWorkerExit(w, completedAbruptly);
}
}
下面3张图是work循环执行getTask时,从队列中取出的任务=null时,就执行ctl-1,
compareAndDecrementWorkerCount(c)这个方法。成功后,返回null,runWork()方法中的while循环就会退出,执行下面的 processWorkerExit(w, completedAbruptly);退出方法
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;
}
// 计算work的数量
int wc = workerCountOf(c);
// Are workers subject to culling?
//allowCoreThreadTimeOut 没有设置,始终=false,
//wc > corePoolSize;这个判断就是work>核心数,即存在非核心work,timed=true
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
//执行work-1,返回null任务
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
//存在非核心work,timed=true,就会执行workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS)这个代码
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
//当非核心work从队列中取出null时,都会执行上边的退出方法,work数量减少至corePoolSize值时,就会
//执行下面的方法,队列就阻塞,调用park()方法。等队列中有新任务进来的时候,会给一个信号释放阻塞继续执行任务。下面会看到释放信号
workQueue.take();
if (r != null)
return r;
//取出任务=null时,就设置timeOut=true,等下一次循环的时候,执行work-1
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
存在非核心work,timed=true,就会执行workQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS)这个代码,从队列中等待keepAliveTime这个时间,还没有取出任务,就返回null。这个work就会退出。被集合works移除,等待被gc回收。
下面进入workQueue.take()
java.util.concurrent.LinkedBlockingDeque#take---->
java.util.concurrent.LinkedBlockingDeque#takeFirst这个方法有个while循环
while ( (x = unlinkFirst()) == null) notEmpty.await(); return x;
取出任务x就返回,否则进入await()
java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject#await()
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
int savedState = fullyRelease(node);
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
//这里进入了阻塞
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
可以看见
LockSupport.park(this);阻塞住了
当添加任务到队列的时候就会看到释放,
workQueue.offer(command)--》
java.util.concurrent.LinkedBlockingDeque#offer(E)
java.util.concurrent.LinkedBlockingDeque#offerLast(E)
java.util.concurrent.LinkedBlockingDeque#linkLast
private boolean linkLast(Node<E> node) {
// assert lock.isHeldByCurrentThread();
if (count >= capacity)
return false;
Node<E> l = last;
node.prev = l;
last = node;
if (first == null)
first = node;
else
l.next = node;
++count;
//释放信号
notEmpty.signal();
return true;
}
notEmpty.signal();释放阻塞
总结,当任务添加到线程池的时候,