前言:
线程池是一个非常重要的知识点,也是池化技术的一个典型应用,相信很多人都有使用线程池的经历,但是对于线程池的实现原理大家都了解吗?本篇文章我们将深入线程池源码来一探究竟。
线程池的起源
背景: 随着计算机硬件的升级换代,使我们的软件具备多线程执行任务的能力。当我们在进行多线程编程时,就需要创建线程,如果说程序并发很高的话,我们会创建大量的线程,而每个线程执行一个时间很短的任务就结束了,这样频繁创建线程,会极大的降低系统性能,增加服务器开销,因为创建线程和销毁线程都需要额外的消耗。
这时我们就可以借助池化技术,来优化这一缺陷,线程池就诞生了。
池化技术的本质是在高并发场景下,为了实现资源复用,减少资源创建销毁等开销,如果并发数很小没有明显优势(资源一直占用系统内存,没有机会被使用)。
池化技术介绍: 什么时池化技术呢?池化技术是一种编程技巧,当程序出现高并发时,能够明显的优化程序,降低系统频繁创建销毁连接等额外开销。我们经常接触到的池化技术有数据库连接池、线程池、对象池等等。池化技术的特点是将一些高成本的资源维护在一个特定的池子(内存)中,规定其最小连接数、最大连接数、阻塞队列,溢出规则等配置,方便统一管理。一般情况下也会附带一些监控,强制回收等配套功能。
池化技术作为一种资源使用技术,典型的使用情形是:
- 获取资源的成本较高的时候
- 请求资源的频率很高且使用资源总数较低的时候
- 面对性能问题,涉及到处理时间延迟的时候
池化技术资源分类:
- 系统调用的系统资源,如线程、进程、内存分配等
- 网络通信的远程资源, 如数据库连接、套接字连接等
线程池的定义和使用
线程池是我们为了规避创建线程,销毁线程额外开销而诞生的,所以说我们定义创建好线程池之后,就不需要自己来创建线程,而是使用线程池调用执行我们的任务。下面我们一起看一下如何定义并创建线程池。
方案一:Executors(仅做了解,推荐使用方案二)
创建线程池可以使用Executors,其中提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口。
ExecutorService 接口是Executor接口的子类接口,使用更为广泛,其提供了线程池生命周期管理的方法,返回 Future 对象。
也就是说我们通过Executors创建线程池,得到ExecutorService
,通过ExecutorService
执行异步任务(实现Runnable接口)
Executors 可以创建一下几种类型的线程池:
-
newCachedThreadPool
创建一个可缓存线程池,如果线程池线程数量过剩,会在60秒后回收掉多余线程资源,当任务书增加,线程不够用,则会新建线程。 - newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
-
newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。 -
newSingleThreadExecutor
创建一个单线程的线程池,只使用唯一的线程来执行任务,可以保证任务按照提交顺序来完成。
方案二:ThreadPoolExecutor
在阿里巴巴开发规范中,规定线程池不允许通过Executors创建,而是通过ThreadPoolExecutor创建。
好处:让写的同学可以更加明确线程池的运行规则,规避资源耗尽的风险。
ThreadPoolExecutor的七大参数:
(1)corePoolSize
核心线程数量,核心线程会一直保留,不会被销毁。
(2)maximumPoolSize
最大线程数,当核心线程不能满足任务需要时,系统就会创建新的线程来执行任务。
(3)keepAliveTime
存活时间,核心线程之外的线程空闲多长时间就会被销毁。
(4)timeUnit
代表线程存活的时间单位。
(5)BlockingQueue
阻塞队列
- 如果正在执行的任务超过了最大线程数,可以存放在队列中,当线程池中有空闲资源就可以从队列中取出任务继续执行。
- 队列类型有如下几种类型:LinkedBlockingQueue ArrayBlockingQueue SynchronousQueue TransferQueue。
(6)threadFactory
线程工厂,用来创建线程的,可以自定义线程,比如我们可以定义线程组名称,在jstack问题排查时,非常有帮助。
(7)rejectedExecutionHandler
拒绝策略,
当所有线程(最大线程数)都在忙,并且任务队列处于满任务的状态,则会执行拒绝策略。
JDK为我们提供了四种拒绝策略,我们必须都得熟悉
- AbortPolicy: 丢弃任务,并抛出异常RejectedExecutionException。 默认
- DiscardPolicy: 丢弃最新的任务,不抛异常。
- DiscardOldestPolicy: 扔掉排队时间最久的任务,也就是最旧的任务。
- CallerRuns: 由调用者(提交异步任务的线程)处理任务。
线程池的实现原理
想要实现一个线程池我们就需要关心ThreadPoolExecutor类,因为Executors创建线程池也是通过new ThreadPoolExecutor对象。
看一下ThreadPoolExecutor
的类继承关系,可以看出为什么通过Executors
创建的线程池返回结果是ExecutorService,因为ThreadPoolExecutor是ExecutorService接口的实现类,而Executors创建线程池本质也是创建的ThreadPoolExecutor 对象。
下面我们一起看一下ThreadPoolExecutor
的源码,首先是ThreadPoolExecutor
内定义的变量,常量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
// 复合类型变量 是一个原子整数 控制状态(运行状态|线程池活跃线程数量) private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0 )); private static final int COUNT_BITS = Integer.SIZE - 3 ; // 低29位 private static final int CAPACITY = ( 1 << COUNT_BITS) - 1 ; // 容量 // 运行状态存储在高位3位 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; // 所有的任务已结束,活跃线程为0,线程过渡到TIDYING状 态,将会执行terminated()钩子方法 private static final int TERMINATED = 3 << COUNT_BITS; // terminated()方法已经完成 // 设置 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; } /** * 阻塞队列 */ private final BlockingQueue<Runnable> workQueue; /** * Lock 锁. */ private final ReentrantLock mainLock = new ReentrantLock(); /** * 工人们 */ private final HashSet<Worker> workers = new HashSet<Worker>(); /** * 等待条件支持等待终止 */ private final Condition termination = mainLock.newCondition(); /** * 最大的池大小. */ private int largestPoolSize; /** * 完成任务数 */ private long completedTaskCount; /** * 线程工厂 */ private volatile ThreadFactory threadFactory; /** * 拒绝策略 */ private volatile RejectedExecutionHandler handler; /** * 存活时间 */ private volatile long keepAliveTime; /** * 允许核心线程数 */ private volatile boolean allowCoreThreadTimeOut; /** * 核心线程数 */ private volatile int corePoolSize; /** * 最大线程数 */ private volatile int maximumPoolSize; /** * 默认拒绝策略 */ private static final RejectedExecutionHandler defaultHandler = new AbortPolicy(); /** * shutdown and shutdownNow权限 */ private static final RuntimePermission shutdownPerm = new RuntimePermission( "modifyThread" ); |
构造器,,支持最少五种参数,最大七中参数的四种构造器:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
public ThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } public ThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { this (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); } public ThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { this (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); } 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; } |
工人,线程池中执行任务的,线程池就是通过这些工人进行工作的,有核心员工(核心线程)和临时工(人手不够的时候,临时创建的,如果空闲时间厂,就会被裁员),
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
private final class Worker extends AbstractQueuedSynchronizer implements Runnable { private static final long serialVersionUID = 6138294804551838833L; // 工人的本质就是个线程 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 ); } /** 工作 */ public void run() { runWorker( this ); } 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) { } } } } |
核心方法,通过线程池执行任务(这也是线程池的运行原理):
- 检验任务
- 获取当前线程池状态
- 判断上班工人数量是否小于核心员工数
- 如果小于则招人,安排工作
- 不小于则判断等候区任务是否排满
- 如果没有排满则任务排入等候区
- 如果排满,看是否允许招人,允许招人则招临时工
- 如果都不行,该线程池无法接收新任务,开始按老板约定的拒绝策略,执行拒绝策略
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public void execute(Runnable command) { if (command == null ) throw new NullPointerException(); int c = ctl.get(); if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true )) return ; c = ctl.get(); } 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 ); } else if (!addWorker(command, false )) reject(command); } |
submit()
方法是其抽象父类定义的,这里我们就可以明显看到submit与execute的区别,通过submit调用,我们会创建RunnableFuture
,并且会返回Future,这里我们可以将返回值类型,告知submit方法,它就会通过泛型约束返回值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public abstract class AbstractExecutorService implements ExecutorService { public Future<?> submit(Runnable task) { if (task == null ) throw new NullPointerException(); RunnableFuture<Void> ftask = newTaskFor(task, null ); execute(ftask); return ftask; } 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; } public <T> Future<T> submit(Callable<T> task) { if (task == null ) throw new NullPointerException(); RunnableFuture<T> ftask = newTaskFor(task); execute(ftask); return ftask; } ... } |
addWorker()是招人的一个方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
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 ; 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 } } 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.add(w); int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; workerAdded = true ; } } finally { mainLock.unlock(); } if (workerAdded) { t.start(); workerStarted = true ; } } } finally { if (! workerStarted) addWorkerFailed(w); } return workerStarted; } |
获取任务的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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 ; } } } |
让员工干活的方法,分配任务,运行任务:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null ; w.unlock(); // allow interrupts boolean completedAbruptly = true ; try { 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 { 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); } } |
到此这篇关于从java源码分析线程池(池化技术)的实现原理的文章就介绍到这了,更多相关Java线程池原理内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://juejin.cn/post/7063379162437779469