zoukankan      html  css  js  c++  java
  • java线程池详解

    学习过程中参考的文献:

    https://www.cnblogs.com/jiawen010/p/11855768.html

    https://blog.csdn.net/zhaohong_bo/article/details/89303522

    https://blog.csdn.net/u013738122/article/details/88595505

    一.线程池简介

    1.线程池的出现

    多线程运行时,系统不断创建和摧毁线程,启动和关闭线程,会消耗系统资源,并造成时间上的浪费,降低效率;过渡切换线程,可能导致系统资源的崩溃;这时,线程池就是最好的选择了。

    2.线程池的概念

    线程池就是一些线程的集合。使用线程池可以很好地提高性能,线程池在系统启动时即创建大量空闲的线程(这句话是错误的,线程池在系统启动时, 并不会立刻创建空闲的线程,文章末尾会详细解释),程序将一个任务传给线程池,线程池就会启动一条线程来执行这个任务(启动而不是创建,是否创建要根据线程池所设置的参数来决定),执行结束以后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个任务。

    3.线程池的工作机制

    1.在线程池模式下,任务是提交给整个线程池,而不是直接提交给某个线程。线程池在拿到任务后,就在内部寻找是否有空闲的线程,如果有,则将任务交给某个空闲的线程

    2.一个线程同时只能执行一个任务,但可以同时向一个线程池提交多个任务

    二.四种常见的线程池

    1.newCacheThreadPool()

    1.简介

    可缓存的线程池。先查看池中有没有以前建立的线程,如果有,就直接使用。如果没有,就建一个新的线程加入池中。空闲线程摧毁的时间为60s,缓存型池通常用于执行一些生存期很短的异步型任务

    其构建源码如下:

    2.实例代码

     1 package com.example.demo.ThreadPool;
     2 
     3 import java.util.concurrent.ExecutorService;
     4 import java.util.concurrent.Executors;
     5 
     6 /**
     7  * @Description: Executors.newCacheThreadPool()
     8  * @author: ZYQ
     9  * @date: 2020/11/11 19:46
    10  */
    11 public class NewCacheThreadPool {
    12     public static void main(String[] args) {
    13         //创建一个可缓存线程池
    14         ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    15         for (int i = 0; i < 10; i++) {
    16             try {
    17                 Thread.sleep(1000);
    18             } catch (InterruptedException e) {
    19                 e.printStackTrace();
    20             }
    21             cachedThreadPool.execute(new Runnable() {
    22                 @Override
    23                 public void run() {
    24                     System.out.println(Thread.currentThread().getName() + "正在被执行");
    25                     try {
    26                         Thread.sleep(1000);
    27                     } catch (InterruptedException e) {
    28                         e.printStackTrace();
    29                     }
    30                 }
    31             });
    32         }
    33         cachedThreadPool.shutdown();
    34     }
    35 }
    newCacheThreadPool
     1 pool-1-thread-1正在被执行
     2 pool-1-thread-2正在被执行
     3 pool-1-thread-2正在被执行
     4 pool-1-thread-1正在被执行
     5 pool-1-thread-1正在被执行
     6 pool-1-thread-1正在被执行
     7 pool-1-thread-2正在被执行
     8 pool-1-thread-2正在被执行
     9 pool-1-thread-1正在被执行
    10 pool-1-thread-2正在被执行
    11 
    12 Process finished with exit code 0
    执行结果

    2.newFixedThreadPool(int n)

    1.简介

    创建一个创建固定大小可重用的线程池。每次提交一个任务就创建一个线程,直到线程达到线程池的最大大小。线程池的大小一旦达到最大值就会保持不变,如果某个线程因为执行异常而结束,那么线程池会补充一个新线程。定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

    其构建源码如下:

    2.示例代码

     1 package com.example.demo.ThreadPool;
     2 
     3 import java.util.concurrent.ExecutorService;
     4 import java.util.concurrent.Executors;
     5 
     6 /**
     7  * @Description: Executors.newFixedThreadPool(int xxx)
     8  * @author: ZYQ
     9  * @date: 2020/11/11 19:53
    10  */
    11 public class NewFixedThreadPool {
    12     public static void main(String[] args) {
    13 
    14         //线程池的大小最好根据系统资源进行设置
    15         int threadNums = Runtime.getRuntime().availableProcessors();
    16         System.out.println(threadNums);
    17 
    18         //创建一个可重用固定个数的线程池
    19         ExecutorService fixedThreadPool = Executors.newFixedThreadPool(threadNums);
    20         for (int i = 0; i < 10; i++) {
    21             fixedThreadPool.execute(new Runnable() {
    22                 @Override
    23                 public void run() {
    24                     System.out.println(Thread.currentThread().getName() + "正在被执行");
    25                     try {
    26                         Thread.sleep(2000);
    27                     } catch (InterruptedException e) {
    28                         e.printStackTrace();
    29                     }
    30                 }
    31             });
    32         }
    33        fixedThreadPool.shutdown();
    34     }
    35 }
    newFixedThreadPool
     1 8
     2 pool-1-thread-3正在被执行
     3 pool-1-thread-1正在被执行
     4 pool-1-thread-2正在被执行
     5 pool-1-thread-4正在被执行
     6 pool-1-thread-5正在被执行
     7 pool-1-thread-6正在被执行
     8 pool-1-thread-7正在被执行
     9 pool-1-thread-8正在被执行
    10 pool-1-thread-3正在被执行
    11 pool-1-thread-7正在被执行
    12 
    13 Process finished with exit code 0
    执行结果

    3.newScheduledThreadPool(int n)

    1.简介

    创建一个大小无限的线程池。此线程池支持定时以及周期性执行任务的需求。

    其构造源码如下:

    2.示例代码

     1 package com.example.demo.ThreadPool;
     2 
     3 import java.util.concurrent.Executors;
     4 import java.util.concurrent.ScheduledExecutorService;
     5 import java.util.concurrent.TimeUnit;
     6 
     7 /**
     8  * @Description: 定长线程池,支持定时及周期性任务执行和延迟执行
     9  * @author: ZYQ
    10  * @date: 2020/11/11 20:09
    11  */
    12 public class NewScheduledThreadPool {
    13     public static void main(String[] args) {
    14 
    15         int threadNums = Runtime.getRuntime().availableProcessors();
    16 
    17         //创建一个定长线程池,支持定时及周期性任务执行和延迟执行
    18         ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(threadNums);
    19 
    20         //延迟1秒执行
    21         scheduledThreadPool.schedule(new Runnable() {
    22             @Override
    23             public void run() {
    24                 System.out.println("延迟1秒执行");
    25             }
    26         }, 1, TimeUnit.SECONDS);
    27 
    28         //延迟1秒后每3秒执行一次
    29         scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
    30             @Override
    31             public void run() {
    32                 System.out.println("延迟1秒后每3秒执行一次");
    33             }
    34         }, 1, 3, TimeUnit.SECONDS);
    35     }
    36 }
    newScheduledThreadPool
     1 延迟1秒执行
     2 延迟1秒后每3秒执行一次
     3 延迟1秒后每3秒执行一次
     4 延迟1秒后每3秒执行一次
     5 延迟1秒后每3秒执行一次
     6 延迟1秒后每3秒执行一次
     7 延迟1秒后每3秒执行一次
     8 延迟1秒后每3秒执行一次
     9 延迟1秒后每3秒执行一次
    10 延迟1秒后每3秒执行一次
    11 延迟1秒后每3秒执行一次
    12 延迟1秒后每3秒执行一次
    13 延迟1秒后每3秒执行一次
    14 延迟1秒后每3秒执行一次
    15 延迟1秒后每3秒执行一次
    16 延迟1秒后每3秒执行一次
    17 延迟1秒后每3秒执行一次
    18 延迟1秒后每3秒执行一次
    19 
    20 Process finished with exit code -1
    执行结果

    4.newSingleThreadExecutor()

    1.简介

    创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

    其构造源码如下:

    2.示例代码

     1 package com.example.demo.ThreadPool;
     2 
     3 import java.util.concurrent.ExecutorService;
     4 import java.util.concurrent.Executors;
     5 
     6 /**
     7  * @Description:
     8  * @author: ZYQ
     9  * @date: 2020/11/11 20:26
    10  */
    11 public class NewSingleThreadPool {
    12     public static void main(String[] args) {
    13         //创建一个单线程化的线程池
    14         ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    15         for (int i = 0; i < 10; i++) {
    16             final int index = i;
    17             singleThreadExecutor.execute(new Runnable() {
    18                 @Override
    19                 public void run() {
    20                     System.out.println(Thread.currentThread().getName() + "正在被执行,打印的值是:" + index);
    21                     try {
    22                         Thread.sleep(3000);
    23                     } catch (InterruptedException e) {
    24                         e.printStackTrace();
    25                     }
    26                 }
    27             });
    28         }
    29         singleThreadExecutor.shutdown();
    30     }
    31 }
    newSingleThreadExecutor
     1 pool-1-thread-1正在被执行,打印的值是:0
     2 pool-1-thread-1正在被执行,打印的值是:1
     3 pool-1-thread-1正在被执行,打印的值是:2
     4 pool-1-thread-1正在被执行,打印的值是:3
     5 pool-1-thread-1正在被执行,打印的值是:4
     6 pool-1-thread-1正在被执行,打印的值是:5
     7 pool-1-thread-1正在被执行,打印的值是:6
     8 pool-1-thread-1正在被执行,打印的值是:7
     9 pool-1-thread-1正在被执行,打印的值是:8
    10 pool-1-thread-1正在被执行,打印的值是:9
    11 
    12 Process finished with exit code 0
    执行结果

    三.利用ThreadPoolExecutor和BlockingQueue自定义创建线程池

    1.自定义创建线程池的原因

    根据以上4种常用线程池的构建源码,可以发现其都是在使用ThreadPoolExecutor来实现。

    其中 newCacheThreadPool 和 newScheduledThreadPool 两种类型的maximumPoolSize都为MAX_INTEGER。这是非常不合理的,可能会导致创建大量的线程,从而导致OOM

    而 FixedThreadPool 和 SingleThreadPool 允许的请求队列(底层实现是LinkedBlockingQueue)长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM

    所以我们最好避免使用Executors创建线程池,主要是避免使用其中的默认实现,那么我们可以自己直接调用ThreadPoolExecutor的构造函数来自己创建线程池。在创建的同时,给BlockQueue指定容量就可以了。

    2. 缓冲队列BlockingQueue简介:

              BlockingQueue是双缓冲队列。BlockingQueue内部使用两条队列,允许两个线程同时向队列一个存储,一个取出操作。在保证并发安全的同时,提高了队列的存取效率。

    3. 常用的几种BlockingQueue:

    • ArrayBlockingQueue(int i):规定大小的BlockingQueue,其构造必须指定大小。其所含的对象是FIFO顺序排序的。

    • LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue,若其构造时指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE来决定。其所含的对象是FIFO顺序排序的。

    • PriorityBlockingQueue()或者(int i):类似于LinkedBlockingQueue,但是其所含对象的排序不是FIFO,而是依据对象的自然顺序或者构造函数的Comparator决定。

    • SynchronizedQueue():特殊的BlockingQueue,对其的操作必须是放和取交替完成。

    4. ThreadPoolExecutor常用参数

        /**
         * 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) { }
    

    1.corePoolSize:

    线程池的基本大小,只有在工作队列满了的情况下才会创建超出这个数量的线程。这里需要注意的是:在刚刚创建ThreadPoolExecutor的时候,线程并不会立即创建,而是要等到有任务提交时才会创建,除非调用了prestartCoreThread/prestartAllCoreThreads事先创建核心线程。核心线程创建后,会一直存在,除非allowCoreThreadTimeOut设置为true(allowCoreThreadTimeOut只控制核心线程)。再考虑到keepAliveTime和allowCoreThreadTimeOut超时参数的影响,所以没有任务需要执行的时候,线程池的大小不一定是corePoolSize。

    2.maximumPoolSize

    线程池中允许的最大线程数,线程池中的当前线程数目不会超过该值。如果队列中任务已满,并且当前线程个数小于maximumPoolSize,那么会创建新的线程来执行任务。这里值得一提的是largestPoolSize,该变量记录了线程池在整个生命周期中曾经出现的最大线程个数。为什么说是曾经呢?因为线程池创建之后,可以调用setMaximumPoolSize()改变运行的最大线程的数目。

    3.keepAliveTime

    如果一个线程处在空闲状态的时间超过了该属性值,就会因为超时而退出。举个例子,如果线程池的核心大小corePoolSize=5,而当前大小poolSize =8,那么超出核心大小的线程,会按照keepAliveTime的值判断是否会超时退出。如果线程池的核心大小corePoolSize=5,而当前大小poolSize =5,那么线程池中所有线程都是核心线程,这个时候线程是否会退出,取决于allowCoreThreadTimeOut。

    4.unit:超时时间的单位

    5.workQueue:工作队列,保存未执行的Runnable 任务

    6.threadFactory:创建线程的工厂类

    7.handler:当线程已满,工作队列也满了的时候,会被调用。被用来实现各种拒绝策略。

    5.自定义线程池示例代码

     1 package com.example.demo.ThreadPool;
     2 
     3 import java.util.concurrent.ArrayBlockingQueue;
     4 import java.util.concurrent.BlockingQueue;
     5 import java.util.concurrent.ThreadPoolExecutor;
     6 import java.util.concurrent.TimeUnit;
     7 
     8 /**
     9  * @Description:
    10  * @author: ZYQ
    11  * @date: 2020/11/11 21:15
    12  */
    13 public class ZiDingYiThreadPool {
    14     public static void main(String[] args) {
    15         //创建数组型缓冲等待队列
    16         BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(10);
    17         //ThreadPoolExecutor: 创建自定义线程池,池中保存的线程数为3,允许最大的线程数为6
    18         ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 50, TimeUnit.MILLISECONDS, bq);
    19 
    20         //创建6个任务
    21         TempThread t1 = new TempThread();
    22         TempThread t2 = new TempThread();
    23         TempThread t3 = new TempThread();
    24         TempThread t4 = new TempThread();
    25         TempThread t5 = new TempThread();
    26         TempThread t6 = new TempThread();
    27 
    28         tpe.execute(t1);
    29         tpe.execute(t2);
    30         tpe.execute(t3);
    31         tpe.execute(t4);
    32         tpe.execute(t5);
    33         tpe.execute(t6);
    34 
    35         //关闭自定义线程池
    36         tpe.shutdown();
    37 
    38     }
    39 }
    40 
    41 class TempThread implements Runnable {
    42 
    43     @Override
    44     public void run() {
    45         //打印正在执行的缓存线程信息
    46         System.out.println(Thread.currentThread().getName() + "正在被执行");
    47         try {
    48             //sleep一秒使得3个任务在分别3个线程上执行
    49             Thread.sleep(1000);
    50         } catch (InterruptedException e) {
    51             e.printStackTrace();
    52         }
    53     }
    54 }
    ZiDingYiThreadPool
    1 pool-1-thread-1正在被执行
    2 pool-1-thread-3正在被执行
    3 pool-1-thread-2正在被执行
    4 pool-1-thread-2正在被执行
    5 pool-1-thread-1正在被执行
    6 pool-1-thread-3正在被执行
    7 
    8 Process finished with exit code 0
    执行结果

    构建线程池的参数如下:

    //创建数组型缓冲等待队列
    BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(10);
    //ThreadPoolExecutor: 创建自定义线程池,池中保存的线程数为3,允许最大的线程数为6
    ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 50, TimeUnit.MILLISECONDS, bq);

    我们创建了6个任务,打印的结果信息是每次输出3个,输出2次就结束了。这是为什么呢?

    我们需要了解一下提交新任务到线程池时的处理流程:

    1. 如果线程池的当前大小还没有达到基本大小(poolSize < corePoolSize),那么就新增加一个线程处理新提交的任务;
    2. 如果当前大小已经达到了基本大小,就将新提交的任务提交到阻塞队列排队,等候处理workQueue.offer(command);
    3. 如果队列容量已达上限,并且当前大小poolSize没有达到maximumPoolSize,那么就新增线程来处理任务;
    4. 如果队列已满,并且当前线程数目也已经达到上限,那么意味着线程池的处理能力已经达到了极限,此时需要拒绝新增加的任务。至于如何拒绝处理新增的任务,取决于线程池的饱和策略RejectedExecutionHandler。

    因此:这个ZiDingYiThreadPool将会创建3个corePoolSize线程先来处理任务;在处理任务时,未被执行的另外3个任务将会进入队列中,队列容量为10,并没有达到上限,不会创建新线程;再执行完任务之后,核心线程会继续执行队列中的任务。因此得到如上的输出结果...

    6.线程池的关闭

    线程池提供了两个关闭方法,shutdownNow和shuwdown方法。

    shutdownNow方法的解释是:线程池拒接收新提交的任务,同时立马关闭线程池,线程池里的任务不再执行

    shutdown方法的解释是:线程池拒接收新提交的任务,同时等待线程池里的任务执行完毕后关闭线程池

    四.注意点和总结

    1.什么是OOM:https://blog.csdn.net/qq_42447950/article/details/81435080?utm_medium=distribute.pc_relevant.none-task-blog-baidulandingword-2&spm=1001.2101.3001.4242

    2.就像文章开头说的,线程池创建完毕时,池中是没有线程的,这一点可以使用ThreadPoolExecutor的getTaskCount()方法来获取总共线程数来进行验证;当任务提交到线程池中时,才会根据线程池本身的参数设定来创建线程,具体方式是上述提交新任务到线程池时的处理流程;线程的数量也会变动,keepAliveTime会控制普通空闲线程的销毁,allowCoreThreadTimeOut设置为true时,keepAliveTime才会控制核心线程的销毁。

    3.少用4种默认的创建线程池方式,多用自定义方式,即可了解源码,也可规避资源耗尽的风险。

     

  • 相关阅读:
    查找mysql数据库中所有包含特定名字的字段所在的表
    redis在windows下安装和PHP中使用
    CentOS 6.3下源码安装LAMP(Linux+Apache+Mysql+Php)环境
    telnet: connect to address 127.0.0.1: Connection refused
    [Java]局域网五子棋
    springboot-web进阶(三)——统一异常处理
    springboot-web进阶(二)——AOP统一处理请求
    springboot-web进阶(一)——表单验证
    springboot快速入门(五)——事务管理
    springboot快速入门(四)——数据库操作
  • 原文地址:https://www.cnblogs.com/yuanweidao/p/13963270.html
Copyright © 2011-2022 走看看