官方+白话讲解Executors、ThreadPoolExecutor线程池使用

Executors:JDK给提供的线程工具类,静态方法构建线程池服务ExecutorService,也就是ThreadPoolExecutor,使用默认线程池配置参数。

    建议:对于大用户,高并发,不易掌控的项目,不建议使用Executors来创建线程池对象。

      对于易于掌控且并发数不高的项目,可以考虑Executors。

ThreadPoolExecutor:线程池对象,实现ExecutorService接口,可以自定义线程池核心线程数、最大线程数、空闲时间、缓冲队列等。

    建议:大用户,高并发,不易于掌控的项目,建议根据物理服务器配置,任务需求耗时,可能存在的并发量,自定义配置ThreadPoolExecutor线程信息。

      一般项目会封装ThreadPoolExecutor工具类,因为需要考虑新手有时会乱用,也方便于统一灵活管理。

一、先说下Executors 创建线程池的三种策略

  1.创建无边界缓存线程池:Executors.newCachedThreadPool()

    无边界缓存界线程池:不限制最大线程数的线程池,且线程有空闲存活时长。

    接着看下JDK Executors.newCachedThreadPool()源码:

    

    源码可以可以看到,该方法创建了一个线程池为:核心线程数0,最大线程数Integer.MAX_VALUE(可以理解为无上限),线程空闲存活时长60,单位TimeUnit.SECONDS秒,缓冲队列是SynchronousQueue的线程池。

    因为最大线程数没有上限,所以,大用户,高并发项目使用时一定要严谨配置。

    关于SynchronousQueue缓冲队列的缓冲数是1,不过每次都被线程池创建取走,所以该缓冲对联永远isEmpty=true。具体细节先百度,后续有时间我再讲解。

  2.创建有边界线程池:Executors.newFixedThreadPool(200)

    有边界线程池:有最大线程数限制的线程池。

    接着看下JDK Executors.newFixedThreadPool(200)源码:

    

    源码可以可以看到,该方法创建了一个线程池为:核心线程数nThreads(200),最大线程数nThreads (200),线程空闲存活时长0,单位TimeUnit.SECONDS秒,缓冲队列是LinkedBlockingQueue的线程池。

    LinkedBlockingQueue这里没有定义长度,也就是说这个缓冲队列的容量没有上限,大用户,高并发项目使用时一定要严谨配置。

  3.创建单线程线程池:Executors.newSingleThreadExecutor()

    单线程线程池:线程池里只有一个线程数,其他都存在缓冲队列里,

    接着看下JDK Executors.newSingleThreadExecutor()源码:

    

    源码可以可以看到,该方法创建了一个线程池为:核心线程数1,最大线程数1,线程空闲存活时长0,单位TimeUnit.MILLISECONDS毫秒,缓冲队列是LinkedBlockingQueue的线程池。

    LinkedBlockingQueue这里没有定义长度,也就是说这个缓冲队列的容量没有上限,大用户,高并发项目使用时一定要严谨配置。

    使用场景:任务需要逐一调度执行。

二、ThreadPoolExecutor自定义配置线程池对象

   通过上面的Executors,我们对创建线程池已经有了点了解。

   下面直接看构造函数的源码,我把参数解释为白话文

   /**
* @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.
缓冲队列,BlockingQueue接口的实现类,根据需求选择他的实现类即可,细节有必要去找度娘。
         常用BlockingQueue有LinkedBlockingQueue和SynchronousQueue
* @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
         缓冲队列已满且已经最大线程数,这时的处理策略
         RejectedExecutionHandler下有多个实现类,根据所需决定
   */
public ThreadPoolExecutor(int corePoolSize,
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;
}

    在开发实战中,对于多线程颇为了解的,我建议根据硬件和软件需求结合,自定义创建ThreadPoolExecutor线程池。

Executors、ThreadPoolExecutor线程池讲解的更多相关文章

  1. ThreadPoolExecutor 线程池的源码解析

    1.背景介绍 上一篇从整体上介绍了Executor接口,从上一篇我们知道了Executor框架的最顶层实现是ThreadPoolExecutor类,Executors工厂类中提供的newSchedul ...

  2. j.u.c系列(01) ---初探ThreadPoolExecutor线程池

    写在前面 之前探索tomcat7启动的过程中,使用了线程池(ThreadPoolExecutor)的技术 public void createExecutor() { internalExecutor ...

  3. 手写线程池,对照学习ThreadPoolExecutor线程池实现原理!

    作者:小傅哥 博客:https://bugstack.cn Github:https://github.com/fuzhengwei/CodeGuide/wiki 沉淀.分享.成长,让自己和他人都能有 ...

  4. 源码剖析ThreadPoolExecutor线程池及阻塞队列

    本文章对ThreadPoolExecutor线程池的底层源码进行分析,线程池如何起到了线程复用.又是如何进行维护我们的线程任务的呢?我们直接进入正题: 首先我们看一下ThreadPoolExecuto ...

  5. 手写一个线程池,带你学习ThreadPoolExecutor线程池实现原理

    摘要:从手写线程池开始,逐步的分析这些代码在Java的线程池中是如何实现的. 本文分享自华为云社区<手写线程池,对照学习ThreadPoolExecutor线程池实现原理!>,作者:小傅哥 ...

  6. ThreadPoolExecutor 线程池的实现

    ThreadPoolExecutor继承自 AbstractExecutorService.AbstractExecutorService实现了 ExecutorService 接口. 顾名思义,线程 ...

  7. 13.ThreadPoolExecutor线程池之submit方法

    jdk1.7.0_79  在上一篇<ThreadPoolExecutor线程池原理及其execute方法>中提到了线程池ThreadPoolExecutor的原理以及它的execute方法 ...

  8. javade多任务处理之Executors框架(线程池)实现的内置几种方式与两种基本自定义方式

    一 Executors框架(线程池) 主要是解决开发人员进行线程的有效控制,原理可以看jdk源码,主要是由java.uitl.concurrent.ThreadPoolExecutor类实现的,这里只 ...

  9. Java并发——ThreadPoolExecutor线程池解析及Executor创建线程常见四种方式

    前言: 在刚学Java并发的时候基本上第一个demo都会写new Thread来创建线程.但是随着学的深入之后发现基本上都是使用线程池来直接获取线程.那么为什么会有这样的情况发生呢? new Thre ...

随机推荐

  1. C语言实现Linux之ls

    ls命令用来显示目标列表. 常用参数: -l    :以长格式显示目录下的内容列表.输出信息从左向右依次包括文件名,文件类型,权限模式,硬连接数,所有者.组.文件大小和文件的最后修改时间等: -a   ...

  2. python总结三

    1.线性表若采用链式存储结构的时候,要求内存中可用存储单位的地址是:连续或者不连续都可以 链式存储去找后继节点或者前驱节点是使用指针来实现的,不需要连续的内存,当然,也可以是连续的内存地址 2. 线性 ...

  3. C语言-memset()

    1. memset()函数原型是extern void *memset(void *buffer, int c, int count)        buffer:为指针或是数组, c:是赋给buff ...

  4. 关于Vue中props的详解

    看一下官方文档: 组件实例的作用域是孤立的.这意味着不能 (也不应该) 在子组件的模板内直接引用父组件的数据.父组件的数据需要通过 prop 才能下发到子组件中. 也就是props是子组件访问父组件数 ...

  5. java面试题——高级篇

    一.集合 Hashmap的原理 源码分析参考文章:http://www.cnblogs.com/xwdreamer/archive/2012/06/03/2532832.html 题目参考文章:htt ...

  6. 微信第三方平台代公众号发起网页授权 48001 api unauthorized 问题

    https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&gr ...

  7. .NET 微服务 2 架构设计理论(一)

    SOA体系架构 面向服务的体系结构 (SOA) ,通过将应用程序分解为多个服务(通常为 HTTP 服务,WCF服务等),将其分为不同类型(例如子系统或层),从而来划分应用程序的结构. 微服务源自 SO ...

  8. OpenCV使用CMake和MinGW的编译安装

    官方教程:https://wiki.qt.io/How_to_setup_Qt_and_openCV_on_Windows 软件环境: Qt:5.11 CMake-3.14.4 OpenCV-4.1. ...

  9. 软件——解决Modelsim10.1d窗口不停弹出问题(一直弹窗)

    博主在编写Verilog HDL时需要用到Modelsim,于是博主便安装了Modelsim10.1d,然后兴高采烈打开准备跑仿真时,打开软件发现Modelsim10.1d的各种窗口在不停弹出,终止进 ...

  10. 【题解】整数划分 [51nod1201] 整数划分 V2 [51nod1259]

    [题解]整数划分 [51nod1201] 整数划分 V2 [51nod1259] 传送门:整数划分 \([51nod1201]\) 整数划分 \(V2\) \([51nod1259]\)** [题目描 ...