java线程池使用及ThreadPoolExecutor源码分析

it2025-07-11  4

文章目录

1线程池基础使用1.1 概述1.2 线程池的优点1.3 Exector继承图1.4 ExecutorService接口1.5 Executors工具类1.5.1 生成各种线程池的方法1.5.2 方法的使用示例1.5.3 各个方法的源码返回ThreadPoolExecutor对象的方法:返回ScheduledThreadPoolExecutor对象的方法:返回ForkJoinPool对象的方法 1.2.5 线程池的工作流程1.2.6 ThreadPoolExecutor参数1.2.7 自定义线程池 ---------分割线------下面内容面试不太涉及---------2.ThreadPoolExecutor源码分析2.1、常用变量的解释2.2、构造方法2.3、提交执行task的过程2.4、addworker源码解析2.5、线程池worker任务单元2.6、核心线程执行逻辑-runworker 3. WorkStealingPool---ForkJoinPool3.1 ForkJoinPool与ThreadPoolExecutor的区别 3.2 可以添加到ForkJoinPool中的任务类型

1线程池基础使用

1.1 概述


线程的创建和销毁消耗的资源都非常大,我们提前创建好多个线程,放入线程池中,使用时直接获取,使用完毕后再归还到线程池中,这样就避免了创建和销毁,实现重复利用。在实际的开发中我们都使用这个方法。java通过Executor这个工厂类向我们提供各种的线程池。

1.2 线程池的优点


减少线程的创建时间,提高相应速度

重复利用线程池中的线程,降低资源消耗

便于线程的管理,比如可以控制 核心池的大小,最大线程数等。

1.3 Exector继承图


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-z8z0t9eZ-1603327309491)(/Users/luca/MarkText-img-Support/Executor继承图.png)]

1.4 ExecutorService接口


ExecutorService: 真正的线程池接口。常见子类ThreadPoolExecutor,ScheduledPoolExecutor, ForkJoinPool

其中定义的三个常用的方法:

Future submit(Callable task): 执行任务,有返回值,一般又来执行 Callable

void shutdown() : 关闭连接池

void execute(Runnable command) : 执行任务/命令,没有返回值,一般用来执行 Runnable

1.5 Executors工具类


1.5.1 生成各种线程池的方法

Executors: 工具类、线程池的工具类,用于创建并返回不同类型的线程池

Executors.newCachedThreadPool(): 创建一个可根据需要创建新线程的线程池

Executors.newFixedThreadPool(n); 创建一个可重用固定线程数的线程池

Executors.newSingleThreadExecutor() : 创建一个只有一个线程的线程池

Executors.newScheduledThreadPool(n): 创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。

下面橙色方块中的是Executors中的方法,返回对应黄色方块中的对象,而黄色方块中的类都是ExecutorService的直接或间接子类.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GKFdMXwV-1603327309500)(/Users/luca/MarkText-img-Support/2020-07-24-10-40-11-image.png)]

1.5.2 方法的使用示例

如何使用工具类提供的方法?以ThreadPoolExecutor为例

class NumThread implements Runnable{ @Override public void run() { for (int i = 0; i <100 ; i++) { System.out.println(Thread.currentThread().getName()+": " + i); } } } public class ThreadPoolTest { public static void main(String[] args) { /*使用工具类创建一个固定大小为10的线程池,其实我们是直到这个线程池的类型是 ThreadPoolExecutor类型,但是所有线程池的父接口都是ExecutorService,所以 我们现将其声明为ExecutorService,之后再做强转*/ ExecutorService executorService = Executors.newFixedThreadPool(10); //将其强制转换 ThreadPoolExecutor service = (ThreadPoolExecutor) executorService; //下面是对线程池的一些设置 service.setCorePoolSize(5); //service.setKeepAliveTime(); service.setMaximumPoolSize(20); executorService.execute(new NumThread()); //executorService.submit(); 用于Callable executorService.shutdown(); } }

1.5.3 各个方法的源码

返回ThreadPoolExecutor对象的方法:
//1.newFixedThreadPool:调用的是ThreadPoolExecutor的构造器 public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); } //2.newSingleThreadExecutor:调用的也是ThreadPoolExecutor的构造器 public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } //3.newCachedThreadPool:调用的还是ThreadPoolExecutor的构造器 public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 10L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
返回ScheduledThreadPoolExecutor对象的方法:
//1.newScheduledThreadPool:调用的是ScheduledThreadPoolExecutor的构造器 public static ScheduledExecutorService newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory) { return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); } //2.newSingleThreadScheduledExecutor:调用的也是ScheduledThreadPoolExecutor的构造器 public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); // 虽然返回的是DelegatedScheduledExecutorService,但其实还是ScheduledThreadPoolExecutor }
返回ForkJoinPool对象的方法
//newWorkStealingPool:调用的是ForkJoinPool的构造器 public static ExecutorService newWorkStealingPool(int parallelism) { return new ForkJoinPool (parallelism, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); }

1.2.5 线程池的工作流程


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-i811OJea-1603327309574)(/Users/luca/MarkText-img-Support/2020-07-24-10-46-48-image.png)]

1.2.6 ThreadPoolExecutor参数


以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; } //自定义线程池 public static void SelfMakingThreadPoolExecutorTest(){ ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 1, //核心线程数为1 2, //最大线程数为2 10, //非核心线程超过10(单位为秒)被闲置,则回收 TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5), //使用ArrayBlockingQueue 里面可以装5个任务 Executors.defaultThreadFactory(); ); }

参数:

corePoolSize - the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set

maximumPoolSize - the maximum number of threads to allow in the pool

keepAliveTime - when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.

unit - the time unit for the keepAliveTime argument

workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method. 这里写的是阻塞队列,阻塞队列也有很多种,更具具体的需求来选择不同的队列。

threadFactory - the factory to use when the executor creates a new thread

这个参数要实现ThreadFactory接口;这个工厂主要指定如何创建一个线程,比如线程的名字是什么,线程的优先级是什么,线程是否为守护线程等

(我们一般不提供这个参数,使用默认的Executors.defaultThreadFactory() )

handler - the handler to use when execution is blocked because the thread bounds and queue capacities are reached

拒绝策略,但所有线程正在使用,已经到达最大线程数,阻塞队列也已经满时,执行拒绝策略。

JDK默认给我们提供了4种拒绝策略:

AbortPolicy:扔掉线程,并抛异常

DiscardPolicy:扔掉,但是不抛异常

DiscardOldestPolicy:扔掉排队时间最久的,把新来的这个线程放入阻塞队列中

CallerRunsPolicy:调用者处理任务,哪一个线程向线程池提交的任务,就把这个任务还给谁去处理

我们也可以自己定义。(我们一般不提供这个参数,使用默认的)

1.2.7 自定义线程池


(我们拿ThreadPoolExecutor为例,其他的也一样) 熟悉了这七个参数后,我们就可以自己创建线程池了。

//自定义线程池 public static void SelfMakingThreadPoolExecutorTest(){ ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 10, TimeUnit.SECONDS, new ArrayBlockingQueue(5)); threadPoolExecutor.execute(new Runnable() { @Override public void run() { System.out.println("自定义线程池"); } }); }

---------分割线------下面内容面试不太涉及---------

2.ThreadPoolExecutor源码分析


2.1、常用变量的解释

// 1. `ctl`,可以看做一个int类型的数字,高3位表示线程池状态,低29位表示worker数量 private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0)); // 2. `COUNT_BITS`,`Integer.SIZE`为32,所以`COUNT_BITS`为29 private static final int COUNT_BITS = Integer.SIZE - 3; // 3. `CAPACITY`,线程池允许的最大线程数。1左移29位,然后减1,即为 2^29 - 1 private static final int CAPACITY = (1 << COUNT_BITS) - 1; // runState is stored in the high-order bits // 4. 线程池有5种状态,按大小排序如下:RUNNING < SHUTDOWN < STOP < TIDYING < TERMINATED private static final int RUNNING = -1 << COUNT_BITS; private static final int SHUTDOWN = 0 << COUNT_BITS; private static final int STOP = 1 << COUNT_BITS; private static final int TIDYING = 2 << COUNT_BITS; private static final int TERMINATED = 3 << COUNT_BITS; // Packing and unpacking ctl // 5. `runStateOf()`,获取线程池状态,通过按位与操作,低29位将全部变成0 private static int runStateOf(int c) { return c & ~CAPACITY; } // 6. `workerCountOf()`,获取线程池worker数量,通过按位与操作,高3位将全部变成0 private static int workerCountOf(int c) { return c & CAPACITY; } // 7. `ctlOf()`,根据线程池状态和线程池worker数量,生成ctl值 private static int ctlOf(int rs, int wc) { return rs | wc; } /* * Bit field accessors that don't require unpacking ctl. * These depend on the bit layout and on workerCount being never negative. */ // 8. `runStateLessThan()`,线程池状态小于xx private static boolean runStateLessThan(int c, int s) { return c < s; } // 9. `runStateAtLeast()`,线程池状态大于等于xx private static boolean runStateAtLeast(int c, int s) { return c >= s; }

2.2、构造方法

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; // 根据传入参数`unit`和`keepAliveTime`,将存活时间转换为纳秒存到变量`keepAliveTime `中 this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }

2.3、提交执行task的过程

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(); // worker数量比核心线程数小,直接创建worker执行任务 if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true))//true表示为核心线程 return; c = ctl.get(); } // worker数量超过核心线程数,任务直接进入队列 if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); // 线程池状态不是RUNNING状态,说明执行过shutdown命令,需要对新加入的任务执行reject()操作。 // 这儿为什么需要recheck,是因为任务入队列前后,线程池的状态可能会发生变化。 if (! isRunning(recheck) && remove(command)) reject(command); // 这儿为什么需要判断0值,主要是在线程池构造方法中,核心线程数允许为0 else if (workerCountOf(recheck) == 0) addWorker(null, false); } // 如果线程池不是运行状态,或者任务进入队列失败,则尝试创建worker执行任务。 // 这儿有3点需要注意: // 1. 线程池不是运行状态时,addWorker内部会判断线程池状态 // 2. addWorker第2个参数表示是否创建核心线程 // 3. addWorker返回false,则说明任务执行失败,需要执行reject操作 else if (!addWorker(command, false)) reject(command); }

2.4、addworker源码解析

private boolean addWorker(Runnable firstTask, boolean core) { retry: // 外层自旋 for (;;) { int c = ctl.get(); int rs = runStateOf(c); /* 这个条件写得比较难懂,我对其进行了调整,和下面的条件等价 (rs > SHUTDOWN) || (rs == SHUTDOWN && firstTask != null) || (rs == SHUTDOWN && workQueue.isEmpty()) 1. 线程池状态大于SHUTDOWN时,直接返回false 2. 线程池状态等于SHUTDOWN,且firstTask不为null,直接返回false 3. 线程池状态等于SHUTDOWN,且队列为空,直接返回false Check if queue empty only if necessary.*/ if (rs >= SHUTDOWN && ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty())) return false; // 内层自旋 for (;;) { int wc = workerCountOf(c); // worker数量超过容量,直接返回false if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)) return false; // 使用CAS的方式增加worker数量。 // 若增加成功,则直接跳出外层循环进入到第二部分 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 } } /*从头到这里,这些代码做的工作就是将线程数量+1,(线程数量就是clt的后29位) 在多线程的状态下+1,为了保证效率,它没有使用sych,所以代码会很多 */ ---------------------------------------------------------------------- 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; // worker的添加必须是串行的,因此需要加锁 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)) { // worker已经调用过了start()方法,则不再创建worker if (t.isAlive()) // precheck that t is startable throw new IllegalThreadStateException(); // worker创建并添加到workers成功 workers.add(w); // 更新`largestPoolSize`变量 int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; workerAdded = true; } } finally { mainLock.unlock(); } // 启动worker线程 if (workerAdded) { t.start(); workerStarted = true; } } } finally { // worker线程启动失败,说明线程池状态发生了变化(关闭操作被执行),需要进行shutdown相关操作 if (! workerStarted) addWorkerFailed(w); } return workerStarted; }

2.5、线程池worker任务单元

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. */ 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的关键所在,使用了线程工厂创建了一个线程。传入的参数为当前worker this.thread = getThreadFactory().newThread(this); } /** Delegates main run loop to outer runWorker */ public void run() { runWorker(this); } // 省略代码... }

2.6、核心线程执行逻辑-runworker

final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; // 调用unlock()是为了让外部可以中断 w.unlock(); // allow interrupts // 这个变量用于判断是否进入过自旋(while循环) boolean completedAbruptly = true; try { // 这儿是自旋 // 1. 如果firstTask不为null,则执行firstTask; // 2. 如果firstTask为null,则调用getTask()从队列获取任务。 // 3. 阻塞队列的特性就是:当队列为空时,当前线程会被阻塞等待 while (task != null || (task = getTask()) != null) { // 这儿对worker进行加锁,是为了达到下面的目的 // 1. 降低锁范围,提升性能 // 2. 保证每个worker执行的任务是串行的 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(); // 执行任务,且在执行前后通过`beforeExecute()`和`afterExecute()`来扩展其功能。 // 这两个方法在当前类里面为空实现。 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 { // 帮助gc task = null; // 已完成任务数加一 w.completedTasks++; w.unlock(); } } completedAbruptly = false; } finally { // 自旋操作被退出,说明线程池正在结束 processWorkerExit(w, completedAbruptly); } }

3. WorkStealingPool—ForkJoinPool


Executor.WorkStealingPool()返回的是ForkJoinPool对象,ForkJoinPool对象的特点:

Fork分叉,join汇总;这个池子就是用来将一个大的任务分解成小的任务,之后在汇总起来

它可以用很少的线程来执行多个子任务

cpu密集型

3.1 ForkJoinPool与ThreadPoolExecutor的区别


ThreadPoolExecutor是有一个线程的集合(存储在HashSet中)和一个任务队列(也就是我们的BlockingQueue),所有的线程从同一个任务队列中取出任务,而ForkJoinPool是每一个线程都有一个单独的队列,当一个线程执行完自己的任务之后,会去其他的线程“偷”任务

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RqNN5wrj-1603327309586)(/Users/luca/MarkText-img-Support/2020-09-02-22-31-32-image.png)]

3.2 可以添加到ForkJoinPool中的任务类型


因为ForkJoinPool是可以拆分任务的,所以我们要求这个任务是可拆分的,可汇总的。所以我们不能继承传统的Runnable或Callerable接口,我们要为他定义一种特殊的类型。这个类就是ForkJoinTask

public abstract class ForkJoinTask<V> implements Future<V>, Serializable { //... }

ForkJoinTask在实际开发中比较原始,我们可以使用RecursiveAction(不带返回值;它叫做“递归动作”,不停的切分不就是一个递归吗?)

public abstract class RecursiveAction extends ForkJoinTask<Void> {}

当然,如果我们需要返回值我们可以继承RecursiveTask类

最新回复(0)