线程池
池化技术
程序的运行的本质:占用系统的资源,优化资源的使用 => 池化技术
线程池、连接池、内存池、对象池…
池化技术:事先准备好一些资源, 有人要用,就来我这里拿,用完之后还给我。
线程池的好处:
- 降低资源的消耗(创建和销毁需要销毁大量时间)
- 提高响应速度
- 方便管理
线程复用、可以控制最大并发数、管理线程
三大方法
// 单例线程池,只有一个线程
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
// 创建固定大小线程数的线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
// 线程缓冲池,可根据需求自动扩容,在性能足够的情况下会尽可能多的创建线程,最大为Integer.MAX_VALUE
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, // 约等于21亿
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
// 创建一个线程池
public class TestExecutors {
public static void main(String[] args) {
// 单例线程池,只有一个线程
//ExecutorService threadPool = Executors.newSingleThreadExecutor();
// 创建有5个线程的线程池
//ExecutorService threadPool = Executors.newFixedThreadPool(5);
// 线程缓冲池,可根据需求自动扩容,在性能足够的情况下会尽可能多的创建线程,最大为Integer.MAX_VALUE 约等于21亿
ExecutorService threadPool = Executors.newCachedThreadPool();
try {
for (int i = 0; i < 10; i++) {
// 使用线程池创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭线程池
threadPool.shutdown();
}
}
}
七大参数
源码
// 使用 Executors 创建线程池的本质是使用 new ThreadPoolExecutor()
// new 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.acc = System.getSecurityManager() == null ?
null : AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
结论:Executors工具类的三大方法只是对ThreadPoolExecutor七大参数的不同需求做封装
源码:
注意:超时时间单位
unit
不需要定义为成员变量,它在初始化中直接转化成了纳秒this.keepAliveTime = unit.toNanos(keepAliveTime);
而参数allowCoreThreadTimeOut
默认为false,即核心线程不会超时等待被销毁,后面会讲到
举例查看线程池参数状态变化
手动使用 ThreadPoolExecutor 创建线程池
public class MyThreadPool {
public static void main(String[] args) {
/**
* int corePoolSize,核心线程池大小(默认开启的线程数)
* int maximumPoolSize,最大线程池大小
* long keepAliveTime,线程存活时间,超时没有调用会被释放
* TimeUnit unit,超时时间单位
* BlockingQueue<Runnable> workQueue,阻塞队列
* ThreadFactory threadFactory,线程工厂,创建线程,一般不动
* RejectedExecutionHandler handler,拒绝执行策略
*/
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
2, 6, 3, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
// 队列满了,再有线程请求不再处理,抛出异常
new ThreadPoolExecutor.AbortPolicy());
// 最大承载:workQueue + maximumPoolSize
// 超过最大承载报拒绝执行异常:java.util.concurrent.RejectedExecutionException
try {
for (int i = 0; i < 9; i++) {
// 使用线程池创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭线程池
threadPool.shutdown();
}
}
}
阻塞队列
-
ArrayBlockingQueue
由数组支持的有界阻塞队列。此队列对元素进行 FIFO(先进先出)排序。队列的头部是在队列中时间最长的元素。队列的尾部是在队列中时间最短的元素。新元素被插入到队列的尾部,队列检索操作获取队列头部的元素。
-
DelayQueue
Delayed元素的无界阻塞队列,其中一个元素只有在其延迟到期时才能被取出。队列的头部是Delayed在过去过期最远的元素。如果没有延迟过期,则没有 head 并且poll将返回null 。当元素的getDelay(TimeUnit.NANOSECONDS)方法返回的值小于或等于零时,就会过期。即使无法使用take或poll删除未过期的元素,它们也会被视为普通元素。例如, size方法返回过期和未过期元素的计数。此队列不允许空元素。
-
LinkedBlockingDeque
基于链接节点的可选有界阻塞双端队列。可选的容量绑定构造函数参数用作防止过度扩展的一种方式。容量(如果未指定)等于Integer.MAX_VALUE 。链接节点在每次插入时动态创建,除非这会使双端队列超出容量。
-
LinkedBlockingQueue
一个基于链表结构的阻塞队列,此队列按 FIFO 排序元素,吞吐量通常要高于 ArrayBlockingQueue。静态工厂方法 Executors.newFixedThreadPool() 使用了这个队列。
-
SynchronousQueue
一个不存储元素的阻塞队列。每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态,吞吐量通常要高于 LinkedBlockingQueue,静态工厂方法 Executors.newCachedThreadPool 使用了这个队列。
-
PriorityBlockingQueue:一个具有优先级的无限阻塞队列。
四种拒绝策略
前提:最大线程池和阻塞队列满了
-
ThreadPoolExecutor.AbortPolicy() 不处理,直接抛出 RejectedExecutionException异常
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { throw new RejectedExecutionException("Task " + r.toString() + " rejected from " + e.toString()); }
-
ThreadPoolExecutor.CallerRunsPolicy() 在调用者的线程(main线程)中执行任务,不会抛出异常
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { r.run(); } }
-
ThreadPoolExecutor.DiscardPolicy() 什么都不做,相当于丢掉任务,不抛异常
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { }
-
ThreadPoolExecutor.DiscardOldestPolicy() 丢弃阻塞队列队头的线程任务,并执行当前请求任务
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { e.getQueue().poll();// poll方法删除队头元素 e.execute(r); } }
执行代码查看线程池状态变化
请结合代码注释理解
初始化:
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
2, 6, 3, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
// 队列满了,再有线程请求不再处理,抛出异常
new ThreadPoolExecutor.AbortPolicy());
当任务请求执行时,如果当前运行的线程少于 corePoolSize(2:线程池大小),就尝试使用给定命令启动一个新线程执行该任务,不论此时线程池中是否有核心线程在空闲状态都会开启新的核心线程。核心线程池的线程在创建后无论有没有任务请求默认都会开启等待;
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
});
TimeUnit.SECONDS.sleep(1);
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
});
// 结果,可以看出并不会直接使用处在空闲的pool-1-thread-1,而是开启了新线程
pool-1-thread-1 OK
pool-1-thread-2 OK
如果核心线程池corePoolSize(2)满了并且线程都在执行任务,再有线程请求则进入阻塞队列workQueue(3)等待线程空闲;
try {
for (int i = 1; i <= 6; i++) {
// 使用线程池创建线程
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
TimeUnit.SECONDS.sleep(1);
System.out.println("ActiveCount=" + threadPool.getActiveCount());
System.out.println("WorkQueue=" + threadPool.getQueue().size());
System.out.println("TaskCount=" + threadPool.getTaskCount());
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭线程池
threadPool.shutdown();
}
// 结果,核心线程池满了,阻塞队列中有三个任务在等待并且队列已经满了
pool-1-thread-1 OK
pool-1-thread-2 OK
ActiveCount=2
WorkQueue=3
TaskCount=6
如果核心线程池和阻塞队列都满了,再有线程请求则促发开启剩余线程(maximumPoolSize - corePoolSize = 4)处理任务;
// 把任务数改成maximumPoolSize + workQueue = 9
for (int i = 1; i <= 9; i++)
// 结果,达到最大线程数,并且等待队列也满了
pool-1-thread-1 OK
pool-1-thread-5 OK
pool-1-thread-2 OK
pool-1-thread-6 OK
pool-1-thread-3 OK
pool-1-thread-4 OK
ActiveCount=6
WorkQueue=3
TaskCount=9
如果最大线程池和阻塞队列都满了(9),再有线程请求则使用拒绝策略handler处理。
// 任务数改成10,已经大于maximumPoolSize + workQueue = 9
for (int i = 1; i <= 10; i++)
// 结果,执行了拒绝策略 AbortPolicy,抛出异常
pool-1-thread-1 OK
pool-1-thread-3 OK
pool-1-thread-2 OK
pool-1-thread-4 OK
pool-1-thread-5 OK
pool-1-thread-6 OK
java.util.concurrent.RejectedExecutionException: Task com.zeng.juc.threadPool.MyThreadPool$$Lambda$1/1831932724@58372a00 rejected from java.util.concurrent.ThreadPoolExecutor@4dd8dc3[Running, pool size = 6, active threads = 6, queued tasks = 3, completed tasks = 0]
如果在之后有的任务执行完并且:
0 <= 正在执行任务的线程数 < maximumPoolSize,当非核心线程超过keepAliveTime unit等待时间就会被销毁,而核心线程默认false不会超时销毁, NowPoolSize=2
for (int i = 1; i <= 6; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
try {
TimeUnit.NANOSECONDS.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
TimeUnit.SECONDS.sleep(5);
System.out.println("ActiveCount=" + threadPool.getActiveCount());
System.out.println("WorkQueue=" + threadPool.getQueue().size());
System.out.println("TaskCount=" + threadPool.getTaskCount());
System.out.println("NowPoolSize=" + threadPool.getPoolSize());
// 结果,可以看出总共执行完了6个任务,执行完后过5秒,非核心线程超时等待被销毁,只剩下非核心线程2个
pool-1-thread-1 OK
pool-1-thread-3 OK
pool-1-thread-2 OK
pool-1-thread-3 OK
pool-1-thread-2 OK
pool-1-thread-1 OK
ActiveCount=0
WorkQueue=0
TaskCount=6
NowPoolSize=2
可以通过设置下列属性为true开启核心线程的超时等待
private volatile boolean allowCoreThreadTimeOut;
public void allowCoreThreadTimeOut(boolean value) {
if (value && keepAliveTime <= 0)
throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
if (value != allowCoreThreadTimeOut) {
allowCoreThreadTimeOut = value;
if (value)
interruptIdleWorkers();
}
}
开启核心线程超时等待后
threadPool.allowCoreThreadTimeOut(true);
,超时会被销毁 NowPoolSize=0
for (int i = 1; i <= 6; i++) {
threadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
try {
TimeUnit.NANOSECONDS.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
threadPool.allowCoreThreadTimeOut(true);
TimeUnit.SECONDS.sleep(5);
System.out.println("ActiveCount=" + threadPool.getActiveCount());
System.out.println("WorkQueue=" + threadPool.getQueue().size());
System.out.println("TaskCount=" + threadPool.getTaskCount());
System.out.println("NowPoolSize=" + threadPool.getPoolSize());
// 结果,可以看出总共执行完了6个任务,执行完后过5秒,非核心线程和非核心线程都超时等待被销毁
pool-1-thread-2 OK
pool-1-thread-3 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-3 OK
pool-1-thread-2 OK
ActiveCount=0
WorkQueue=0
TaskCount=6
NowPoolSize=0
最大线程池大小应该如何设置(调优)
- CPU密集型
几核CPU就定义几,保证CPU效率最高
int processors = Runtime.getRuntime().availableProcessors();
- IO密集型
判断程序中非常消耗IO的线程个数 n,设置 最大线程池 > n