常用例子
ThreadPoolExecutor是java中线程池类,平时可能我们并不直接用到它,我们可能是通过调用Executors来使用线程池的
java.util.concurrent.ExecutorService executorService = Executors.newFixedThreadPool(2);
当然了,通过Executors构建ThreadPoolExecutor有好几个方式,这里我们只是拿出一种来分析下它的原理。
其实,在Executors的newFixedThreadPool方法里面也是创建一个ThreadPoolExecutor对象的
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
Executors只是帮助我们封装了ThreadPoolExecutor的创建,但有时我们需要自己定制化ThreadPoolExecutor的一些相关功能,其实我们是可以这样的
//==>>arguments of constructor
int corePoolSize = 0;
int maximumPoolSize = Integer.MAX_VALUE;
long keepAliveTime = 60L;
TimeUnit timeUnit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new java.util.concurrent.LinkedBlockingQueue<Runnable>();
ThreadFactory threadFactory = Executors.defaultThreadFactory();
RejectedExecutionHandler defaultHandler = new java.util.concurrent.ThreadPoolExecutor.AbortPolicy();
//==>>
ThreadPoolExecutor threadPoolExecutor = new java.util.concurrent.ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
timeUnit,
workQueue,
threadFactory,
defaultHandler);
threadPoolExecutor.execute(new Runnable(){
@Override
public void run() {
System.out.println("execute run method.");
}});
threadPoolExecutor.shutdown();
这里已经把ThreadPoolExecutor的构造方法需要相关参数已经罗列出来,这样有助于后续我们定制化相关功能。
好了,大概了解了ThreadPoolExecutor需要的参数,下面我们通过源码深入了解它的原理。
通过源码的分析,在最后我们会总结出它的工作原理的。
/*
* A handler for tasks that cannot be executed by a ThreadPoolExecutor.
*/
public interface java.util.concurrent.RejectedExecutionHandler {
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
这是任务添加失败时,线程池拒绝策略接口,就是添加任务失败时,会调用rejectedExecution这个方法。
构造函数参数
int corePoolSize,有新task,先创建新Thread来处理task,一直新创建直到corePoolSize个线程
int maxinumPoolSize,当线程数达到corePoolSize后,新task会被放到阻塞队列,如果阻塞队列也放不下,则新创建线程来处理task,直到创建maxinuxPoolSize个线程
long keepAliveTime,当线程数大于corePoolSize,或者allowCoreThreadTimeOut为true时,线程获取阻塞等待队列里的任务的超时时间,否则,会一直阻塞等待。
TimeUnit timeUnit,keepAliveTime的时间单位
BlockingQueue<Runnable> workQueue,存放task的阻塞队列
ThreadFactory threadFactory,使用工厂模式创建新线程时
RejectedExecutionHandler handler,当线程超过corePoolSize,阻塞队列也放不下task,线程数而且也超过maxinumPoolSize时,会拒绝task,调用handler.rejectedExecution(..)方法拒绝
其实,还有另外一个属性allowCoreThreadTimeOut,不过不在构造函数来传值
/**
* false:默认值,当thread空闲时,且队列里没任务,则thread阻塞在queue.take()方法,从而保证thread不退出。
* true:当thread空闲时,且队列里没任务,而通过queue.poll(keepAliveTime)获取任务超时时,则thread退出,值为true时,keepAliveTime值要大于0。
*/
private volatile boolean allowCoreThreadTimeOut;
提交任务
##public void execute(Runnable command)
A.如果当前工作线程数小于核心线程数(corePoolSize)
1.如果当前工作线程数小于核心线程数,添加一个新的工作线程
2.工作线程数增加1(使用了CAS原子操作自增,保证了操作的线程安全性)
3.创建一个新的工作线程(当前任务作为第一个任务)
4.将新创建的工作线程添加到线程池(HashSet<Worker> workers)
5.1如果成功添加了当前任务,则启动线程执行任务(并设置任务启动成功的标记)
5.2如果任务启动失败,则对于任务启动失败相关的处理。
5.2.1从线程池中剔除掉任务
5.2.2工作线程数减一(使用CAS操作,保证了操作的线程安全性)
5.3添加任务到核心工作线程失败,则将任务添加到阻塞队列排队等待处理。
B.如果当前工作线程数已经大于等于核心线程数
1.如果当前工作线程数已经大于等于核心线程数,则将任务放进阻塞队列(workQueue.offer(command))
2.如果阻塞队列已经达到最大容量不能再放任务,则添加新的工作线程(最大的线程数量是maxinumPoolSize,由构造函数传值)
3.如果阻塞队列满了而且线程线也达到maxinumPoolSize,则会拒绝任务,默认拒绝任务的处理策略(ThreadPoolExecutor.AbortPolicy())会抛出异常,当然,我们也可以写我们自己实现的拒绝处理策略。
过程参照图
线程执行任务
##final void runWorker(Worker w)
核心线程的执行是个不断循环的过程
1.取出线程绑定的任务,
1.1.如果线程绑定第一个任务存在则执行第一个任务
1.2.如果没有第一个任务,则从阻塞队列头部取出一个任务执行
1.3.如果队列是空的,且条件A(线程数 > corePoolSize 或者 allowCoreThreadTimeOut为true)为true,则阻塞一定的时间(keepAliveTime由构造函数传参),阻塞超时则返回null任务;如果条件A为false,则会一直等待直到线程被中断。
2.核心线程执行任务
2.1.如果可以取到任务,执行完任务则循环第1步,执行任务时,如果我们需要在执行任务前后加自己的业务逻辑,可以实现ThreadPoolExecutor的承继类,重写beforeExecute和afterExecute方法,从而实现自己需要在执行任务前后的业务逻辑
过程参照图
优雅关闭
##public void shutdown()设置状态为SHUTDOWN,这样会使得不再接收新的任务
空闲的线程会被中断(Thread.interrupt()),空闲:也许线程刚刚执行完一个任务,Worker的锁被shutdown方法获得,则thread会被interrupt
正在执行任务的线程(由于持有锁,所以shutdown方法不会interrupt它,它可以继续执行队列里的任务)在执行完列队里的任务后,也会退出结束线程。
最后状态设置为TERMINATED
关闭
(相对于shutdown(),并不优雅)
##public List<Runnable> shutdownNow()设置状态为STOP,这样会使得不再接收新的任务
所有的线程会被中断(Thread.interrupt()),不管线程是正在执行任务还是空闲,都会被interrupt
队列里的任务会被取出返回,当然了,那些正在执行任务不能保证是否执行完成。
最后状态设置为TERMINATED
提交任务任务完成通知
##提交任务task,并返回任务完成通知对象Future<T> t
##public <T> Future<T> submit(Runnable task, T result)
#########################################################
向ThreadPoolExecutor提交一个任务,线程异步执行任务,
Future对象t.get()方法调用会阻塞,直到任务执行完。
提交任务调用方法:
public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
其中newTaskFor方法:protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new FutureTask<T>(runnable, value);
}
看看下面FutureTask的源码,可以看出FutureTask既是Runnable对象,也是Future对象其中RunnableFuture接口:
public interface RunnableFuture<V> extends Runnable, Future<V> {...}
下面先看看FutureTask作为Future对象时的get()方法源码:
public class FutureTask<V> implements RunnableFuture<V> {
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L); //1处
return report(s);
}
/**
* Awaits completion or aborts on interrupt or timeout.
*
* @param timed true if use timed waits
* @param nanos time to wait, if timed
* @return state upon completion
*/
private int awaitDone(boolean timed, long nanos) throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos); //2处
}
else
LockSupport.park(this); //3处
}
}
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t); //4处
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
}
从以上源码,get()方法里,如果任务还没结束(任务结束,可能是任务正常执行完成,或者是发生了异常),会调用1处的awaitDone()方法,
awaitDone()方法里,如果任务结束则返回;否则,会调用3处的LockSupport.park(this)当前线程会被挂起,阻塞住,
直到调用了LockSupport.unpark(Thread thread)才会唤醒线程,而在finishCompletion()方法里的4处会调用LockSupport.unpark(..)方法,
在任务正常结束或者执行过程出现异常都调用finishCompletion()方法,则线程就会唤醒,接着get()方法就可以顺利运行下去,也就是任务结束了。
再看看FutureTask作为Runnable对象时,执行任务的run方法:
//执行任务的run方法
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call(); //5处
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
这里貌似没看到构造函数传进来的runnable对象调用run()方法,只有源码“5处”调用了callable的call方法,其实,看构造函数的源码“0处”,runnable对象已经被封装了一层,再返回一个适配器。this.callable = Executors.callable(runnable, result);
已经调用了Executors.callable方法封装了一层。
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
看看RunnableAdapter的源码:static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
所以可以看出Callable的call其实已经是先执行了Runnable的run方法,也是先执行了任务了,完了才会返回result。在执行完任务完,会将状态设置成NORMAL
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
然后finishCompletion方法里,源码“4处”,会调用LockSupport.unpark(t)唤醒正在等待执行结果的线程。