【Java开发】JUC进阶 04:线程池详解
创始人
2024-05-29 06:50:52
0

1 线程池介绍

由于频繁创建销毁线程要调用native方法比较消耗资源,为了保证内核的充分利用,所以引入了线程池的概念。

📌 线程池优点

  • 降低资源消耗

  • 提高响应速度

  • 方便管理

📌 创建线程池

  • 使用Executors创建

  • 使用ThreadPoolExecutor创建

📌 工作流程

2 Executors创建线程池

📌 三大方法

  • ExecutorService threadPool = Executors.newSingleThreadExecutor();--创建单个线程

  • ExecutorService threadPool = Executors.newFixedThreadPool(5);--创建固定大小的线程池

  • ExecutorService threadPool = Executors.newCachedThreadPool();--创建不固定大小的线程池

📌 代码举例

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class ExecutorsDemo {public static void main(String[] args) {ExecutorService threadPool = Executors.newSingleThreadExecutor();
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);
//        ExecutorService threadPool = Executors.newCachedThreadPool();try {//使用线程池创建线程池for (int i = 0; i < 5; i++) {threadPool.execute(()->{System.out.println(Thread.currentThread().getName()+" Ok");});}} catch (Exception e) {e.printStackTrace();} finally {threadPool.shutdown();}}
}

3 ThreadPoolExecutor创建线程池

📌 七大参数说明

  1. corePoolSize:核心线程数量,线程池维护线程的最少数量

  1. maximumPoolSize:线程池维护线程的最大数量

  1. keepAliveTime:线程池除核心线程外的其他线程的最长空闲时间,超过该时间的空闲线程会被销毁

  1. unit:keepAliveTime的单位,TimeUnit中的几个静态属性:NANOSECONDS、MICROSECONDS、MILLISECONDS、SECONDS

  1. workQueue:线程池所使用的任务缓冲队列

  1. threadFactory:线程工厂,用于创建线程,一般用默认的即可

  1. handler:线程池对拒绝任务的处理策略

📢 官方推荐ThreadPoolExecutor创建线程池

阿里代码规范如下:

源码解析👇

//1.newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue()));
}
//2.newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue());
}
//3.newCachedThreadPool
public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE, //21亿60L, TimeUnit.SECONDS,new SynchronousQueue());
}public ThreadPoolExecutor(int corePoolSize, // 核心线程数int maximumPoolSize, // 最大线程数 long keepAliveTime, // 存活时间TimeUnit unit, // 存活时间单位BlockingQueue workQueue, // 阻塞队列ThreadFactory threadFactory, // 线程工厂RejectedExecutionHandler handler //拒绝策略) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,threadFactory, defaultHandler);
}

可以看到Executors创建线程池的三个方法都调用了ThreadPoolExecutor!

4 四大拒绝策略

📌 UML图

📌 要点

  • AbortPolicy:被拒绝了抛出异常

  • CallerRunsPolicy:使用调用者所在线程执行,就是哪里来的回哪里去

  • DiscardOldestPolicy: 当触发拒绝策略,只要线程池没有关闭的话,丢弃阻塞队列 workQueue 中最老的一个任务,并将新任务加入

  • DiscardPolicy:直接丢弃,其他啥都没有

4.1 AbortPolicy

ThreadPoolExecutor 默认AbortPolicy拒绝策略

public class AbortPolicyDemo {public static void main(String[] args) {//自定义线程池!ExecutorService threadPool = new ThreadPoolExecutor(3,//核心线程为35,//最大线程数是5,包括核心线程10,TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),//阻塞队列数Executors.defaultThreadFactory());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();}}
}

控制台输出:

4.2 CallerRunsPolicy

public class CallerRunsPolicyDemo {public static void main(String[] args) {//自定义线程池!ExecutorService threadPool = new ThreadPoolExecutor(3,//核心线程为35,//最大线程数是5,包括核心线程10,TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),//阻塞队列数Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());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();}}
}

控制台输出:

📢 可以看到,多出来的两个线程回到了主线程,因为这10个线程都是从主线程丢到线程池的。

4.3 DiscardPolicy

它会尝试丢掉任务队列中的最早任务,也不会抛出异常。

public class DiscardOldestPolicyDemo {public static void main(String[] args) {//自定义线程池!ExecutorService threadPool = new ThreadPoolExecutor(3,//核心线程为35,//最大线程数是5,包括核心线程10,TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),//阻塞队列数Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardOldestPolicy());try {for (int i = 0; i < 8; i++) {threadPool.execute(()->{try {//添加等待时间,防止过早结束TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+" OK");});}//第九个线程,他会尝试插入,替代最老的线程threadPool.execute(()->{System.out.println(Thread.currentThread().getName()+" OK11");});} catch (Exception e) {e.printStackTrace();} finally {threadPool.shutdown();}}
}

控制台输出:

📢 可以看到总数还是8个线程,而且“0K11”输出了,说明其中一个线程被顶掉了。

4.4 DiscardOldestPolicy

public class DiscardPolicyDemo {public static void main(String[] args) {//自定义线程池!ExecutorService threadPool = new ThreadPoolExecutor(3,//核心线程为35,//最大线程数是5,包括核心线程10,TimeUnit.SECONDS,new LinkedBlockingQueue<>(3),//阻塞队列数Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());try {for (int i = 0; i < 8; i++) {threadPool.execute(()->{try {//添加等待时间,防止过早结束TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+" OK");});}//第九个线程,他会尝试插入,替代最老的线程threadPool.execute(()->{System.out.println(Thread.currentThread().getName()+" OK11");});} catch (Exception e) {e.printStackTrace();} finally {threadPool.shutdown();}}
}

控制台输出:

📢 第9个线程被丢掉了!

相关内容

热门资讯

【NI Multisim 14...   目录 序言 一、工具栏 🍊1.“标准”工具栏 🍊 2.视图工具...
银河麒麟V10SP1高级服务器... 银河麒麟高级服务器操作系统简介: 银河麒麟高级服务器操作系统V10是针对企业级关键业务...
不能访问光猫的的管理页面 光猫是现代家庭宽带网络的重要组成部分,它可以提供高速稳定的网络连接。但是,有时候我们会遇到不能访问光...
AWSECS:访问外部网络时出... 如果您在AWS ECS中部署了应用程序,并且该应用程序需要访问外部网络,但是无法正常访问,可能是因为...
Android|无法访问或保存... 这个问题可能是由于权限设置不正确导致的。您需要在应用程序清单文件中添加以下代码来请求适当的权限:此外...
北信源内网安全管理卸载 北信源内网安全管理是一款网络安全管理软件,主要用于保护内网安全。在日常使用过程中,卸载该软件是一种常...
AWSElasticBeans... 在Dockerfile中手动配置nginx反向代理。例如,在Dockerfile中添加以下代码:FR...
AsusVivobook无法开... 首先,我们可以尝试重置BIOS(Basic Input/Output System)来解决这个问题。...
ASM贪吃蛇游戏-解决错误的问... 要解决ASM贪吃蛇游戏中的错误问题,你可以按照以下步骤进行:首先,确定错误的具体表现和问题所在。在贪...
月入8000+的steam搬砖... 大家好,我是阿阳 今天要给大家介绍的是 steam 游戏搬砖项目,目前...