线程池
线程池就是创建若干个可执行的线程放入一个池(容器)中
为什么要用线程池,
降低资源的消耗
减少了创建和销毁线程的次数,
每个工作线程都可以被重复利用
可以控制最大并发数
线程池的创建,并说出几种常见的线程池
Alibaba开发手册明确规定,线程池不允许使用Executor去创建,而是通过ThreadPoolExecutor的方式。
先介绍使用Executors创建的方式
ExecutorService e1 = Executors.newSingleThreadExecutor();//创建单个线程 1
ExecutorService e2 = Executors.newFixedThreadPool(5);//创建一个固定的线程大小 0-5
ExecutorService e3 = Executors.newCachedThreadPool();//可伸缩的 0-Integer.MAX_VALUE 21亿左右
try {
for (int i = 0; i < 10; i++) {
e1.execute(() -> {
System.out.println(Thread.currentThread().getName() + " OK");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
e1.shutdown();
}
调用e1.execute的结果
newSingleThreadExecutor();//创建单个线程
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK
pool-1-thread-1 OK 最多只有一个线程在执行
调用e2.execute的结果
newFixedThreadPool(5);//创建一个固定的线程大小
pool-2-thread-3 OK
pool-2-thread-3 OK
pool-2-thread-3 OK
pool-2-thread-3 OK
pool-2-thread-3 OK
pool-2-thread-3 OK
pool-2-thread-2 OK
pool-2-thread-1 OK
pool-2-thread-4 OK
pool-2-thread-5 OK 最多有五个线程在执行
调用e3.execute的结果
newCachedThreadPool();//可伸缩的大小,最大值为Integer.MAX_VALUE
pool-3-thread-5 OK
pool-3-thread-10 OK
pool-3-thread-8 OK
pool-3-thread-3 OK
pool-3-thread-2 OK
pool-3-thread-7 OK
pool-3-thread-4 OK
pool-3-thread-9 OK
pool-3-thread-6 OK
pool-3-thread-1 OK 最多有10个线程在执行
源码分析核心参数
public ThreadPoolExecutor(int corePoolSize,//核心线程池大小 比如说当前开放了2个窗口
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;
}
创建线程池的方法如下:
最大承载线程数量=Deque.size+maximumPoolSize
超过这个数量线程池就会抛出异常
线程池的四种拒绝策略(重点)
默认拒绝策略:AbortPolicy() 当提交的线程无法处理的时候 直接抛出一个异常
CallerRunsPolicy() 哪来的回哪去 比如说是main线程提供的,那么最后会交给Main线程执行
DiscardPolicy() 丢弃策略 队列满了,丢掉新任务,
DiscardOldPolicy 丢弃最老的任务
推荐观看
https://www.bilibili.com/video/BV1B7411L7tE?p=23&t=1093.1