11.1、多线程的概念
线程池(英语:thread pool ) :一种线程使用模式。线程过多会带来调度开销,进而影响缓存局部性和整体性能。而线程池维护着多个线程,等待着监督管理者分配可并发执行的任务。这避免了在处理短时间任务时创建与销毁线程的代价。线程池不仅能够保证内核的充分利用,还能防止过分调度。
线程池的优势:线程池做的工作只要是控制运行的线程数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量,超出数量的线程排队等候,等其他线程执行完毕,再从队列中取出任务来执行。
11.2、主要特点
- 降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的销耗。
- 提高响应速度:当任务到达时,任务可以不需要等待线程创建就能立即执行。
- 提高线程的可管理性:线程是稀缺资源,如果无限制的创建,不仅会销耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。·
- Java 中的线程池是通过Executor框架实现的,该框架中用到了Executor,Executors ,Execu torService ,ThreadPoolExecutor这几个类。
11.3、线程池类的架构关系
11.4、线程池分类
- Executors.newFixedThreadPool(int):一池N线程
- Executors.newSingleThreadExecutor():一个任务一个任务的执行,一池一线程
- Executors.newCacheThreadPool():线程池根据需求创建线程,可扩容。
案例演示
package com.ae.juc.threadPool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolDemo1 { public static void main(String[] args) { //一池5线程 【模拟银行5个窗口】 ExecutorService threadPool1 = Executors.newFixedThreadPool(5); //一池1线程 【模拟银行1个窗口】 ExecutorService threadPool2 = Executors.newSingleThreadExecutor(); //一池可扩容线程 ExecutorService threadPool3 = Executors.newCachedThreadPool(); //20个客户办业务 try { for (int i = 1; i <= 20; i++) { threadPool3.execute(() -> { System.out.println(Thread.currentThread().getName() + " 办理业务"); }); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool1.shutdown(); } } }
11.5、线程池底层原理
查看三个创建线程的底层代码,发现他们创建线程的方式都是一样的,都是调用new ThreadPoolExecutor(),传入不同的参数来实现的。
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
11.6、线程池七个参数
/** * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters. * * @param corePoolSize the number of threads to keep in the pool, even * if they are idle, unless {@code allowCoreThreadTimeOut} is set * @param maximumPoolSize the maximum number of threads to allow in the * pool * @param 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. * @param unit the time unit for the {@code keepAliveTime} argument * @param workQueue the queue to use for holding tasks before they are * executed. This queue will hold only the {@code Runnable} * tasks submitted by the {@code execute} method. * @param threadFactory the factory to use when the executor * creates a new thread * @param handler the handler to use when execution is blocked * because the thread bounds and queue capacities are reached * @throws IllegalArgumentException if one of the following holds:<br> * {@code corePoolSize < 0}<br> * {@code keepAliveTime < 0}<br> * {@code maximumPoolSize <= 0}<br> * {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} * or {@code threadFactory} or {@code handler} is null */ 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; }
corePoolSize:常驻线程数量【例如银行有5个窗口】 maximumPoolSize:最大线程数量【银行最大可以开10个窗口】 keepAliveTime:线程存活时间【例如银行多出来的窗口多久关闭】 unit:时间的单位 workQueue:阻塞队列,常驻线程数据都被占用完了,那么这些任务就会放到阻塞队列中排队等待 threadFactory:线程工厂,用于创建线程的 handler:拒绝策略【银行办理业务,常驻5个窗口和最大10个窗口都已经满了,这时候银行就不在接收新顾客,叫他们去其它银行办理,这就是拒绝策略】
11.7、线程池底层工作流程和拒绝策略
11.7.1、工作原理
- 在创建了线程池后,开始等待请求
- 当调用 execute() 方法添加一个请求任务时,线程池会做出如下判断:
- 如果正在运行的线程数量小于 corePoolSize,那么马上创建线程运行这个任务
- 如果正在运行的线程数量大于或等于 corePoolSize,那么将这个任务 放入队列
- 如果这个时候队列满了且正在运行的线程数量还小于 maximumPoolSize,那么还是要创建非核心线程立刻运行这个任务
- 如果队列满了且正在运行的线程数量大于或等于 maximumPoolSize,那么线程池会 启动饱和拒绝策略来执行
- 当一个线程完成任务时,它会从队列中取下一个任务来执行
- 当一个线程无事可做超过一定的时间(keepAliveTime)时,线程会判断:
- 如果当前运行的线程数大于 corePoolSize,那么这个线程就会被停掉
- 所以线程池的所有任务完成后,它最终会收缩到 corePoolSize 的大小
11.7.2、如何设置合理参数
根据自己的要求合理配置即可
// 自定义线程池 ExecutorService threadPool = new ThreadPoolExecutor( 2, // 线程池中的常驻核心线程数 5, // 最大线程数 2L,// 活跃时间 TimeUnit.SECONDS, new LinkedBlockingQueue<>(3), // 任务队列数 Executors.defaultThreadFactory(), // AbortPolicy 拒绝策略 new ThreadPoolExecutor.AbortPolicy());
11.7.3、线程池的拒绝策略
什么是拒绝策略?
等待队列已经排满了,再也塞不下新任务了。同时,线程池中的 max 线程也达到了,无法继续为新任务服务。这个时候我们就需要拒绝策略机制合理地处理这个问题
有哪些拒绝策略?
AbortPolicy()
直接抛出 RejectExecutionException 异常阻止系统正常运行
package com.ae.juc.threadPool; import java.util.concurrent.*; public class ThreadPoolDemo2 { public static void main(String[] args) { //创建线程池 ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 2, 5, 2, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());//拒绝策略 //处理20个任务 try { for (int i = 1; i <= 20; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + " 办理业务"); }); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }
运行结果
pool-1-thread-1 办理业务 pool-1-thread-2 办理业务 pool-1-thread-2 办理业务 pool-1-thread-2 办理业务 pool-1-thread-2 办理业务 pool-1-thread-3 办理业务 pool-1-thread-4 办理业务 pool-1-thread-5 办理业务 java.util.concurrent.RejectedExecutionException: Task com.ae.juc.threadPool.ThreadPoolDemo2$$Lambda$1/1023892928@4dd8dc3 rejected from java.util.concurrent.ThreadPoolExecutor@6d03e736[Running, pool size = 5, active threads = 5, queued tasks = 0, completed tasks = 2] at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063) at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830) at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379) at com.ae.juc.threadPool.ThreadPoolDemo2.main(ThreadPoolDemo2.java:20)
CallerRunsPolicy()
“调用者运行” 一种调节机制,该策略既不会抛弃任务,也不会抛出异常,而是将某些任务回退到调用者,从而降低新任务的流量。
package com.ae.juc.threadPool; import java.util.concurrent.*; public class ThreadPoolDemo2 { public static void main(String[] args) { //创建线程池 ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 2, 5, 2, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());//拒绝策略 //处理20个任务 try { for (int i = 1; i <= 20; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + " 办理业务"); }); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }
运行结果
pool-1-thread-1 办理业务 pool-1-thread-3 办理业务 pool-1-thread-2 办理业务 pool-1-thread-2 办理业务 main 办理业务 pool-1-thread-5 办理业务 pool-1-thread-5 办理业务 pool-1-thread-1 办理业务 pool-1-thread-3 办理业务 pool-1-thread-4 办理业务 main 办理业务 main 办理业务 pool-1-thread-2 办理业务 pool-1-thread-1 办理业务 pool-1-thread-5 办理业务 main 办理业务 pool-1-thread-2 办理业务 pool-1-thread-1 办理业务 pool-1-thread-3 办理业务 pool-1-thread-2 办理业务
DiscardOldestPolicy()
抛弃队列中等待最久的任务,然后把当前任务加入队列中尝试再次提交当前任务。
package com.ae.juc.threadPool; import java.util.concurrent.*; public class ThreadPoolDemo2 { public static void main(String[] args) { //创建线程池 ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 2, 5, 2, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy());//拒绝策略 //处理20个任务 try { for (int i = 1; i <= 20; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + " 办理业务"); }); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }
运行结果
pool-1-thread-1 办理业务 pool-1-thread-5 办理业务 pool-1-thread-4 办理业务 pool-1-thread-3 办理业务 pool-1-thread-2 办理业务 pool-1-thread-4 办理业务 pool-1-thread-5 办理业务 pool-1-thread-1 办理业务
DiscardPolicy()
该策略默默地丢弃无法处理的任务,不予任何处理也不抛出异常。如果允许任务丢失,这是最好的一种策略
package com.ae.juc.threadPool; import java.util.concurrent.*; public class ThreadPoolDemo2 { public static void main(String[] args) { //创建线程池 ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 2, 5, 2, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());//拒绝策略 //处理20个任务 try { for (int i = 1; i <= 20; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + " 办理业务"); }); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }
运行结果
pool-1-thread-1 办理业务 pool-1-thread-4 办理业务 pool-1-thread-4 办理业务 pool-1-thread-4 办理业务 pool-1-thread-3 办理业务 pool-1-thread-2 办理业务 pool-1-thread-4 办理业务 pool-1-thread-5 办理业务
11.8、自定义线程池
package com.ae.juc.threadPool; import java.util.concurrent.*; public class ThreadPoolDemo2 { public static void main(String[] args) { //创建线程池 ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 2, 5, 2, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());//拒绝策略 //处理20个任务 try { for (int i = 1; i <= 20; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + " 办理业务"); }); } }catch (Exception e){ e.printStackTrace(); }finally { threadPool.shutdown(); } } }