引用举例:
10年前单核CPU电脑,假的多线程,像马戏团小丑玩多个球,CPU需要来回切换。
现在是多核电脑,多个线程各自跑在独立的CPU上,不用切换效率高。
线程池的特点:复用既有线程;控制最大线程并发数;管理线程资源。
线程池的优势:
线程池做的工作主要是控制运行的线程数量,如果线程数量超过了最大数量,超出数量的线程排队等候,等线程任务执行完毕,再从队列中取出任务来执行。
Java中的线程池是通过Executor框架实现的,该框架中用到了Executor,ExecutorService,ThreadPoolExecutor这几个类。
Executor接口是顶层接口,只有一个execute方法,过于简单。通常不使用它,而是使用ExecutorService接口。
(2)ExecutorService接口
(3)AbstractExecutorService抽象类和ThreadPookExecutor实现类
结构:顶层接口Executor(execute) --> 子接口ExecutorService(submit shutdown) --> 抽象类AbstractExecutorService --> 实现类ThreadPoolExecutor
那么问题来了,怎么创建一个连接池对象呢?通常使用Executors工具类
架构图可以看到Executors工具类,有没有联想到Collections,Arrays等。没错,可以用它快速创建线程池。
List list = Arrays.asList("");
ExecutorService threadPool = Executors.newCachedThreadPool();
直接编码演示:每种连接池的效果
(1)固定大小线程池
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
//线程池的声明ExecutorService 底层接口只有一个声明方法太简单 ,所以使用executorService接口
//固定大小线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
//线程池执行任务
//可以把lambda表达式理解为简洁的匿名函数.
//我们先声明一个函数式接口(函数式接口:就是只有一个抽象方法的接口.
// lambda表达式和方法引用,只能用在函数式接口上),比较一下lambda表达式和匿名函数
executorService.execute(() -> {
System.out.println(Thread.currentThread().getName()+"执行了任务");
});
}
//当任务执行完了不会立马销毁销毁,会等待新的任务过来,手动销毁线程池
executorService.shutdown();
}
}
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
//线程池的声明ExecutorService 底层接口只有一个声明方法太简单 ,所以使用executorService接口
//固定大小线程池
//ExecutorService executorService = Executors.newFixedThreadPool(5);
//无限大小线程池
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
//线程池执行任务
//可以把lambda表达式理解为简洁的匿名函数.
//我们先声明一个函数式接口(函数式接口:就是只有一个抽象方法的接口.
// lambda表达式和方法引用,只能用在函数式接口上),比较一下lambda表达式和匿名函数
executorService.execute(() -> {
System.out.println(Thread.currentThread().getName()+"执行了任务");
});
}
//当任务执行完了不会立马销毁销毁,会等待新的任务过来,手动销毁线程池
executorService.shutdown();
}
}
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
//线程池的声明ExecutorService 底层接口只有一个声明方法太简单 ,所以使用executorService接口
//固定大小线程池
//ExecutorService executorService = Executors.newFixedThreadPool(5);
//无限大小线程池
//ExecutorService executorService = Executors.newCachedThreadPool();
//单个大小的线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 100; i++) {
//线程池执行任务
//可以把lambda表达式理解为简洁的匿名函数.
//我们先声明一个函数式接口(函数式接口:就是只有一个抽象方法的接口.
// lambda表达式和方法引用,只能用在函数式接口上),比较一下lambda表达式和匿名函数
executorService.execute(() -> {
System.out.println(Thread.currentThread().getName()+"执行了任务");
});
}
//当任务执行完了不会立马销毁销毁,会等待新的任务过来,手动销毁线程池
executorService.shutdown();
}
}
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
System.out.println("定时任务初始化时间" + System.currentTimeMillis());
//固定周期执行
scheduledExecutorService.scheduleAtFixedRate(() -> {
//System.currentTimeMillis()计算方式与时间的单位转换
//延迟时间意义,需要矫正时间。
System.out.println(Thread.currentThread().getName() + "定时任务执行了" + System.currentTimeMillis());
}, 5, 10, TimeUnit.SECONDS);
// scheduledExecutorService.schedule(() -> {
// //System.currentTimeMillis()计算方式与时间的单位转换
// System.out.println(Thread.currentThread().getName()+"定时任务执行了"+System.currentTimeMillis());
// }, 10, TimeUnit.SECONDS);
}
}
上述案例中的四个方法的本质都是ThreadPoolExecutor的实例化对象,只是具体参数值不同。
具体流程:
重要的事情说三遍:以下重要:以下重要:以下重要:
线程池初始化之后,在创建了线程池后,线程池中的线程数为0。
向线程池提交一个任务,当调用execute()方法添加一个请求任务时,线程池会做出如下判断:
如果正在运行的线程数量小于corePoolSize,那么马上创建线程运行这个任务;
如果正在运行的线程数量大于或等于corePoolSize,那么将这个任务放入阻塞队列;
如果这个时候队列满了且正在运行的线程数量还小于maximumPoolSize,那么还是要创建非核心线程立刻运行这个任务;
如果队列满了且正在运行的线程数量大于或等于maximumPoolSize,那么线程池会启动饱和拒绝策略来执行。
(简述面试版本)
在《阿里巴巴java开发手册》中指出了线程资源必须通过线程池提供,不允许在应用中自行显示的创建线程,这样一方面是线程的创建更加规范,可以合理控制开辟线程的数量;另一方面线程的细节管理交给线程池处理,优化了资源的开销。
而线程池不允许使用Executors去创建,而要通过ThreadPoolExecutor方式,这一方面是由于jdk中Executor框架虽然提供了如newFixedThreadPool()、newSingleThreadExecutor()、newCachedThreadPool()等创建线程池的方法,但都有其局限性,不够灵活;使用ThreadPoolExecutor有助于大家明确线程池的运行规则,创建符合自己的业务场景需要的线程池,避免资源耗尽的风险。
不推荐使用Executors工具类初始化线程池,因为他们都可能导致OOM。推荐使用ThreadPoolExecutor构造方法创建线程池
一般我们创建线程池时,为防止资源被耗尽,任务队列都会选择创建有界任务队列,但种模式下如果出现任务队列已满且线程池创建的线程数达到你设置的最大线程数时,这时就需要你指定ThreadPoolExecutor的RejectedExecutionHandler参数即合理的拒绝策略,来处理线程池"超载"的情况。
ThreadPoolExecutor自带的拒绝策略如下:
例子:
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5));
for (int i = 0; i < 20; i++) {
threadPoolExecutor.submit(() -> {
System.out.println(Thread.currentThread().getName() + "执行了任务");
});
}
}
}
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5),Executors.defaultThreadFactory(),new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 20; i++) {
threadPoolExecutor.submit(() -> {
System.out.println(Thread.currentThread().getName() + "执行了任务");
});
}
}
}
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());
for (int i = 0; i < 20; i++) {
int finalI = i;
threadPoolExecutor.submit(() -> {
System.out.println(Thread.currentThread().getName() + "执行了任务"+ finalI);
});
}
}
}
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy());
for (int i = 0; i < 20; i++) {
int finalI = i;
threadPoolExecutor.submit(() -> {
System.out.println(Thread.currentThread().getName() + "执行了任务"+ finalI);
});
}
}
}
以上内置的策略均实现了RejectedExecutionHandler接口,也可以自己扩展RejectedExecutionHandler接口,定义自己的拒绝策略
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5), Executors.defaultThreadFactory(),
(Runnable r, java.util.concurrent.ThreadPoolExecutor executor) ->{
System.out.println("执行了拒绝策略(自定义拒绝策略)");
});
for (int i = 0; i < 20; i++) {
int finalI = i;
threadPoolExecutor.submit(() -> {
System.out.println(Thread.currentThread().getName() + "执行了任务"+ finalI);
});
}
}
}
自定义线程池:
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
//自定义线程池
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5));
for (int i = 0; i < 20; i++) {
threadPoolExecutor.submit(() -> {
System.out.println(Thread.currentThread().getName() + "执行了任务");
});
}
}
}