一篇文章带你了解Java中ThreadPool线程池

目录

  • ThreadPool
    • 线程池的优势
    • 线程池的特点
  • 1 线程池的方法
    • (1) newFixedThreadPool
    • (2) newSingleThreadExecutor
    • (3) newScheduledThreadPool
    • (4) newCachedThreadPool
  • 2 线程池底层原理
    • 3 线程池策略及分析
      • 拒绝策略
      • 如何设置maximumPoolSize大小

    ThreadPool

    线程池的优势
    线程池做的工作主要是控制运行的线程数量,处理过程中将任务放入队列,然后在线程创建后启动这些任务,如果线程数量超过了最大数量,超出的线程排队等候,等待其他线程执行完毕,再从队列中取出任务来执行

    线程池的特点
    线程复用、控制最大并发数、管理线程
    • 降低资源消耗。重复利用已创建的线程,降低创建和销毁线程的开销
    • 提高响应速度。当任务到达时,任务可以不需要等待线程创建就能立刻执行
    • 提高线程的可管理性。使用线程池可以对线程进行统一的分配、调优和监控



    1 线程池的方法
    执行长期任务性能好,创建一个线程池,一池有N个固定的线程,可以控制线程最大并发数,有固定线程数的线程池[
    ExecutorService threadPool = Executors.newFixedThreadPool(N);

    单个任务执行,它只会使用单个工作线程,一池一线程
    ExecutorService threadPool = Executors.newSingleThreadExecutor();

    执行短期异步任务,可缓存线程池,线程池根据需要创建新线程,但在先前构造的线程可以复用,也可灵活回收空闲的线程,可扩容的池
    ExecutorService threadPool = Executors.newCachedThreadPool();

    周期性线程池;支持定时及周期性任务执行

    ExecutorService threadPool = Executors.newScheduledThreadPool();


    (1) newFixedThreadPool
    可以控制线程最大并发数的线程池:
    public class FixedThreadPool {private static AtomicInteger num = new AtomicInteger(0); private static ExecutorService executorService = Executors.newFixedThreadPool(2); public static void main(String[] args) {countSum c= new countSum(); //将coutSum作为Task,submit至线程池for (int i = 0; i < 2; i++) {executorService.submit(c); }//Task执行完成后关闭executorService.shutdown(); }static class countSum implements Runnable{@Overridepublic void run() {for (int i = 0; i < 500; i++) {try{System.out.println("Thread - "+Thread.currentThread().getName()+" count= "+ num.getAndIncrement()); Thread.sleep(100); }catch (Exception e){e.printStackTrace(); }}}}}

    结果:
    一篇文章带你了解Java中ThreadPool线程池
    文章图片


    (2) newSingleThreadExecutor
    只会使用唯一的工作线程执行任务的线程池:
    public class SingleThreadExecutor {private static AtomicInteger num = new AtomicInteger(0); private static ExecutorService executorService = Executors.newSingleThreadExecutor(); public static void main(String[] args) {//将coutSum作为Task,submit至线程池for (int i = 0; i < 2; i++) {executorService.submit(new countSum()); }//Task执行完成后关闭executorService.shutdown(); }static class countSum implements Runnable{@Overridepublic void run() {for (int i = 0; i < 500; i++) {try{System.out.println("Thread - "+Thread.currentThread().getName()+" count= "+ num.getAndIncrement()); Thread.sleep(100); }catch (Exception e){e.printStackTrace(); }}}}}

    结果:
    一篇文章带你了解Java中ThreadPool线程池
    文章图片


    (3) newScheduledThreadPool
    传参值为corePoolSize大小,支持定时及周期性任务执行
    延期执行示例:调用schedule方法,三个参数:Task,Delay,TimeUnit
    public class ScheduledThreadPool {// corePoolSize = 2private static ScheduledExecutorService service = Executors.newScheduledThreadPool(2); public static void main(String[] args) {System.out.println("Thread - "+Thread.currentThread().getName()+" BEGIN "+ new Date()); service.schedule(new print(),5, TimeUnit.SECONDS); service.shutdown(); }static class print implements Runnable{@Overridepublic void run() {for (int i = 0; i < 10; i++) {try{System.out.println("Thread - "+Thread.currentThread().getName()+" Delay 5 second and sleep 2 second "+ new Date()); Thread.sleep(2000); }catch (Exception e){e.printStackTrace(); }}}}}

    结果:
    一篇文章带你了解Java中ThreadPool线程池
    文章图片

    定时执行示例:调用scheduleAtFixedRate方法,四个参数:Task,initialDelay,Period,TimeUnit
    public class ScheduledThreadPool {// corePoolSize = 1private static ScheduledExecutorService service = Executors.newScheduledThreadPool(1); public static void main(String[] args) {System.out.println("Thread - "+Thread.currentThread().getName()+" BEGIN "+ new Date()); service.scheduleAtFixedRate(new print(),5,3,TimeUnit.SECONDS); }static class print implements Runnable{@Overridepublic void run() {System.out.println("Thread - "+Thread.currentThread().getName()+" Delay 5 second and period 3 second "+ new Date()); }}}

    结果:
    一篇文章带你了解Java中ThreadPool线程池
    文章图片


    (4) newCachedThreadPool
    可缓存线程池,如果线程池长度超过处理需要,回收空闲线程,若无可回收,则新建线程。即若前一个任务已完成,则会接着复用该线程:
    public class CachedThreadPool {private static AtomicInteger num = new AtomicInteger(0); private static ExecutorService service = Executors.newCachedThreadPool(); public static void main(String[] args) {countSum c = new countSum(); for (int i = 0; i < 3; i++) {try {service.submit(c); Thread.sleep(1000); }catch (Exception e){e.printStackTrace(); }}service.shutdown(); }static class countSum implements Runnable{@Overridepublic void run() {for (int i = 0; i < 1000; i++) {System.out.println("Thread - "+Thread.currentThread().getName()+" countSum= "+num.getAndIncrement()); }}}}

    结果:Thread.sleep(1000)即sleep一秒,上个任务完成可继续复用该线程,不需要创建新的线程
    一篇文章带你了解Java中ThreadPool线程池
    文章图片

    若将Tread.sleep(1000)注释掉,你会发现有3个线程在跑
    一篇文章带你了解Java中ThreadPool线程池
    文章图片

    若感兴趣可以去了解一下它们的底层源码,对于CachedThreadPool而言,可新建线程最大数量为INTEGER.MAXIMUM

    2 线程池底层原理
    以newFixedThreadPool为例
    public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue()); }

    public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler); }

    线程池七大参数
    • corePoolSize:线程池中的常驻核心线程数
    • maximumPoolSize:线程池中能够容纳同时执行的最大线程数,必须大于1
    • keepAliveTime:多余的空闲线程的存活时间;当前池中线程数量超过corePoolSize时,当空闲时间达到keepAliveTime时,多余线程会被销毁
    • unit:keepAliveTime的单位
    • workQueue:任务队列,被提交但尚未执行的任务
    • threadFactory:表示生成线程池中工作线程的线程工厂,用于创建线程,一般默认
    • handler:拒绝策略,表示当队列满了,并且工作线程大于等于线程池的最大线程数时如何来拒绝请求执行的runnable的策略
    一篇文章带你了解Java中ThreadPool线程池
    文章图片

    线程池四大流程
    1)创建线程池后,开始等待请求
    2)当调用execute()方法添加一个请求任务时,线程池会做以下判断:
    • 如果正在运行的线程数量小于corePoolSize,马上创建线程执行任务
    • 如果正在运行的线程数量大于等于corePoolSize,将该任务放入等待队列
    • 如果等待队列已满,但正在运行线程数量小于max,创建非核心线程执行任务
    • 如果队列满了且正在运行的线程数量大于max,线程池会启动饱和拒绝策略
    3)当一个线程完成任务时,会从等待队列中取下一个任务来执行
    4)当空闲线程超过keepAliveTime定义时间,会判断:
    • 如果当前运行线程大于corePoolSize,该线程销毁
    • 所有线程执行完任务后,线程个数恢复到corePoolSize大小



    3 线程池策略及分析 Note:阿里巴巴JAVA开发手册:线程池不允许使用Executors去创建线程池,而是通过使用ThreadPoolExecutor的方式自定义线程池,规避资源耗尽的风险
    Executors返回的线程池对象的弊端:
    1)FixedThreadPool和SingleThreadPool:
    ?允许请求队列长度为Integer.MAX_VALUE,可能会堆积大量请求导致OOM
    2)CachedThreadPool和ScheduledThreadPool:
    ?允许创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程导致OOM



    拒绝策略
    1)AbortPolicy
    ?直接抛出RejectedExecutionException异常阻止系统正常运行
    2)CallerRunsPolicy
    ?"调用者运行"的调节机制,该策略既不会抛弃任务,也不会抛出异常,而是将某些任务回退到调用者,从而降低新任务的流量
    3)DiscardPolicy
    ?该策略抛弃无法处理的任务,不予任何处理也不抛出异常。如果允许任务丢失,这是最好的一种策略
    4)DiscardOldestPolicy
    【一篇文章带你了解Java中ThreadPool线程池】?抛弃队列中等待最久的任务,然后把当前任务加入队列中尝试再次提交当前任务



    如何设置maximumPoolSize大小
    Runtime.getRuntime().availableProcessors()方法获取核数
    CPU密集型
    ?maximumPoolSize设为核数+1
    IO密集型
    ?maximumPoolSize设为核数/阻塞系数
    以上就是一篇文章-带你了解ThreadPool线程池的详细内容,更多关于ThreadPool线程池的资料请关注脚本之家其它相关文章!

      推荐阅读