【Java8源码分析】线程池-Executor与ExecutorService的全面剖析

时间:2022-10-23 09:20:18

转载请注明出处:http://blog.csdn.net/linxdcn/article/details/72828362


1 Executor接口与ExecutorService接口

1.1 介绍

Executor接口很简单,只定义了一个execute函数用来提交一个Runnable的任务。该方式提交的任务不能获取返回值,因此无法判断任务是否执行成功。

public interface Executor {
void execute(Runnable command);
}

ExecutorService继承Executor接口,提供比Executor更多的功能,可以获取任务执行完的返回值。

public interface ExecutorService extends Executor {

// 启动一个关闭命令,不再接受新任务
// 当所有已提交任务执行完后,就关闭
// 如果已经关闭,则调用没有其他作用
void shutdown();

// 试图停止所有正在执行的活动任务,暂停处理正在等待的任务
// 并返回等待执行的任务列表
List<Runnable> shutdownNow();

boolean isShutdown();
boolean isTerminated();

// 提交任务
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);

// 批量提交任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;

<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;

<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}

1.2 Executor使用

程序

public class ExecutorDemo {

public static void main(String[] args) {
Executor executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(new Task());
}
}

}

class Task implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
}

输出

pool-1-thread-2 is running
pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running
pool-1-thread-4 is running
pool-1-thread-5 is running
pool-1-thread-2 is running
pool-1-thread-2 is running
pool-1-thread-2 is running
pool-1-thread-1 is running

1.3 ExecutorService使用

程序

public class ExecutorDemo {

public static void main(String[] args) throws Exception{
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<String>> res = new LinkedList<>();
for (int i = 0; i < 10; i++) {
Future future = executor.submit(new Task());
res.add(future);
}

for (Future<String> f : res) {
System.out.println(f.get() + " is returning");
}
}

}

class Task implements Callable<String> {
@Override
public String call() {
System.out.println(Thread.currentThread().getName() + " is running");
return Thread.currentThread().getName();
}
}

输出

pool-1-thread-1 is running
pool-1-thread-1 is returning
pool-1-thread-4 is running
pool-1-thread-3 is running
pool-1-thread-5 is running
pool-1-thread-2 is running
pool-1-thread-5 is running
pool-1-thread-3 is running
pool-1-thread-4 is running
pool-1-thread-1 is running
pool-1-thread-5 is running
pool-1-thread-2 is returning
pool-1-thread-3 is returning
pool-1-thread-4 is returning
pool-1-thread-5 is returning
pool-1-thread-1 is returning
pool-1-thread-4 is returning
pool-1-thread-3 is returning
pool-1-thread-5 is returning
pool-1-thread-5 is returning

2 接口创建

ExecutorExecutorService的创建需通过工厂类Executors创建:

(1)newFixedThreadPool

    public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}

初始化一个指定线程数的线程池,即使线程空闲,也不会释放线程

(2)newCachedThreadPool

    public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

初始化一个可以缓存线程的线程池,在没有任务执行时,当线程的空闲时间超过keepAliveTime,会自动释放线程资源,当提交新任务时,如果没有空闲线程,则创建新线程执行任务,会导致一定的系统开销。

(3)newSingleThreadExecutor

    public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}

初始化的线程池中只有一个线程,如果该线程异常结束,会重新创建一个新的线程继续执行任务,唯一的线程可以保证所提交任务的顺序执行

(4)newScheduledThreadPool

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}

初始化的线程池可以在指定的时间内周期性的执行所提交的任务

(5)newWorkStealingPool

    public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}

这是java1.8推出一个新函数,创建一个 work-stealing 线程池,使用目前机器上可用的处理器作为它的并行级别,并可以使用多个队列来减少竞争。


3 ThreadPoolExecutor类

由第二部分可知,除了newScheduledThreadPool使用ScheduledThreadPoolExecutornewWorkStealingPool使用ForkJoinPool以外,其余的工厂方法都使用了ThreadPoolExecutor类创建。

3.1 构造函数

    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;
}

ThreadPoolExecutor构造函数的可定制参数很多,下面一一说明:

(1)corePoolSize与maximumPoolSize

  • 线程池中的线程数,即使这部分线程空闲,也不会被销毁
  • 如果一个新任务提交,且创建的线程数少于corePoolSize,则新的线程被创建,即使已经创建的线程当中有空闲线程
  • 如果已经创建的线程大于corePoolSize,且小于maximumPoolSize,会先把任务提交到阻塞队列,在阻塞队列满的情况下,才会新建线程
  • 线程池中的线程数不可能大于maximumPoolSize

(2)keepAliveTime与unit

  • keepAliveTime代表线程空闲时的存活时间,即当线程没有任务执行时,继续存活的时间;默认情况下,该参数只在线程数大于corePoolSize时才有用
  • unit则为keepAliveTime的时间单位

(3)workQueue

  • 添加策略

    • 正在执行的线程小于corePoolSize,创建新线程
    • 正在执行的线程大于等于corePoolSize,把任务添加到阻塞队列
    • 阻塞队列满了,且正在执行的线程小于maximumPoolSize,创建新线程
    • 否则拒绝任务
  • 阻塞队列类型

    • ArrayBlockingQueue:基于数组结构的有界阻塞队列,按FIFO排序任务;
    • LinkedBlockingQuene:基于链表结构的阻塞队列,按FIFO排序任务,吞吐量通常要高于ArrayBlockingQuene;
    • SynchronousQuene:一个不存储元素的阻塞队列,每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量通常要高于LinkedBlockingQuene;
    • priorityBlockingQuene:具有优先级的*阻塞队列;

(4)threadFactory

创建线程的工厂,通过自定义的线程工厂可以给每个新建的线程设置一个具有识别度的线程名。

(5)handler

线程池的饱和策略,当阻塞队列满了,且没有空闲的工作线程,如果继续提交任务,采取的处理策略。

3.2 属性域

public class ThreadPoolExecutor extends AbstractExecutorService {
// 用一个Integer来存储线程池状态,和线程数
// 其中高三位是状态,低29位是线程数
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;

// 高三位111,接收新任务,处理阻塞队列任务
private static final int RUNNING = -1 << COUNT_BITS;
// 高三位000,不接收新任务,处理阻塞队列任务
private static final int SHUTDOWN = 0 << COUNT_BITS;
// 高三位001,不接收新任务,不处理阻塞队列任务, 而且中断运行中任务
private static final int STOP = 1 << COUNT_BITS;
// 高三位010,所有线程均中断,woker数量为0
private static final int TIDYING = 2 << COUNT_BITS;
// 高三位011,线程池中断完成
private static final int TERMINATED = 3 << COUNT_BITS;

// 计算ctl值,或者从ctl值中提取状态码或线程数
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }

3.2 execute方法

ThreadPoolExecutor实现了Executor和ExecutorService接口,下面先来看看与execute(Runnable command)相关的方法:

    public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();

int c = ctl.get();
// 如果线程数小于corePoolSize
if (workerCountOf(c) < corePoolSize) {
// 新建一个core线程
if (addWorker(command, true))
return;
c = ctl.get();
}
// 线程数大于corePoolSize,或者新建线程不成功
if (isRunning(c) && workQueue.offer(command)) {
// 成功将任务添加进阻塞队列后,重新更新ctl值
int recheck = ctl.get();
// 如果此时ThreadPoolExecutor已经关闭了
if (! isRunning(recheck) && remove(command))
reject(command);
// 或者线程均被释放了,新建一个线程
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 阻塞队列满了,则尝试新建非core线程
else if (!addWorker(command, false))
reject(command);
}

// 添加线程的函数
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);

if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;

for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
// 采用cas算法更新ctl值
if (compareAndIncrementWorkerCount(c))
break retry;
// 失败则重新尝试
c = ctl.get();
if (runStateOf(c) != rs)
continue retry;
}
}

// 更新ctl值成功后,添加线程
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
// 进入临界区
try {
int rs = runStateOf(ctl.get());

if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
// workers是HashSet<Worker>结构,存储了所有的workers
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
// worker的启动
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}

总结来说,execute方法,要不就是新建一个worker执行任务,要不就将任务添加到阻塞队列中,后续后其他worker来执行,具体规则已经在第2部分总结。

那么worker又是个什么东东?还有它是如何执行的呢?接下来研究研究这个类。

3.3 worker类

首先来看以下worker类

    // Worker继承自AbstractQueuedSynchronizer同步器
// 有空再研究研究这个同步器,评价说设计得非常巧妙
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{

private static final long serialVersionUID = 6138294804551838833L;

// 保存了Thread和Runnable
final Thread thread;
Runnable firstTask;

volatile long completedTasks;

Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}

// run函数
public void run() {
// 实际上是调用了以下这个函数
runWorker(this);
}
}

worker类的核心run方法是通过调用ThreadPoolExecutor中的runWorker实现的,下面来看看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 {
// 调用getTask从阻塞队列获取任务
while (task != null || (task = getTask()) != null) {
// 任务执行前加锁
w.lock();
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
// 开始执行任务
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);
}
}

// 从阻塞队列中获取任务
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 {
// 主要实现
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}

3.4 submit方法

下面来看看ExecutorService接口中的submit方法

    // 本质上把Callable包装成一个FutureTask,然后提交给execute函数执行
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
// 把Callable包装成一个FutureTask
RunnableFuture<T> ftask = newTaskFor(task);
// 通过execute调用
execute(ftask);
return ftask;
}

看过了execute方法的实现后,再来看submit方法就很简单了,本质上把Callable包装成一个FutureTask,然后提交给execute函数执行。

后面再写一篇详细分析一下 Runnable、Callable、Executor、Future、FutureTask这几个类源代码。

3.5 shutdown和shutdownNow

shutdown是按过去执行已提交任务的顺序发起一个有序的关闭,但是不接受新任务。如果已经关闭,则调用没有其他作用。

shutdownNow尝试停止所有的活动执行任务、暂停等待任务的处理,并返回等待执行的任务列表。在从此方法返回的任务队列中排空(移除)这些任务。并不保证能够停止正在处理的活动执行任务,但是会尽力尝试。 此实现通过 Thread.interrupt() 取消任务,所以无法响应中断的任何任务可能永远无法终止。


转载请注明出处:http://blog.csdn.net/linxdcn/article/details/72828362