java 线程池初步涉足

2024-09-03 00:32
文章标签 java 线程 初步 涉足

本文主要是介绍java 线程池初步涉足,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

   先看以下代码,是我们创建线程池的一种方式:

ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

  可以进入Executors类看一下,java创建线程池的四种方式,分别有以下四个大类:

(1)newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程(空闲线程超过存活时间的可以回收),若无可回收,则新建线程。

(2)newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

(3)newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

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

    当然在Executors中创先以上四种线程池的方式还有很多,一会有所涉及。

    我们现在进入Executors类看看创建上述四种线程池有哪些方式:

(1)newFixedThreadPool

    /*** Creates a thread pool that reuses a fixed number of threads* operating off a shared unbounded queue.  At any point, at most* {@code nThreads} threads will be active processing tasks.* If additional tasks are submitted when all threads are active,* they will wait in the queue until a thread is available.* If any thread terminates due to a failure during execution* prior to shutdown, a new one will take its place if needed to* execute subsequent tasks.  The threads in the pool will exist* until it is explicitly {@link ExecutorService#shutdown shutdown}.** @param nThreads the number of threads in the pool* @return the newly created thread pool* @throws IllegalArgumentException if {@code nThreads <= 0}*/public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}/*** Creates a thread pool that reuses a fixed number of threads* operating off a shared unbounded queue, using the provided* ThreadFactory to create new threads when needed.  At any point,* at most {@code nThreads} threads will be active processing* tasks.  If additional tasks are submitted when all threads are* active, they will wait in the queue until a thread is* available.  If any thread terminates due to a failure during* execution prior to shutdown, a new one will take its place if* needed to execute subsequent tasks.  The threads in the pool will* exist until it is explicitly {@link ExecutorService#shutdown* shutdown}.** @param nThreads the number of threads in the pool* @param threadFactory the factory to use when creating new threads* @return the newly created thread pool* @throws NullPointerException if threadFactory is null* @throws IllegalArgumentException if {@code nThreads <= 0}*/public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),threadFactory);}

     这边有两种方式是用来创建newFixedThreadPool线程池的,一种是直接传入线程的个数,另外一种是传进线程的个数,还有线程工厂(ThreadFactory)。有些任务需求对于如何创建线程有自己安排,所以需要传入自己实现ThreadFactory接口的线程工厂类。仔细看,其实这两个方法都使用了类ThreadPoolExecutor。可以去类ThreadPoolExecutor中看看里面构造函数中参数的意思,其构造函数代码如下:可以看到他调用了this(....)构造函数,我顺便把他底层的构造函数都写在后面,方便查看。

       public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);} /*** 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)

这里面一共有六个参数,分别如下:

corePoolSize是线程池中所维持的线程池大小。这些线程即使是空闲状态,也会存在于线程池中,不会被销毁。这个线程池的核心线程数也可以设置为0,像newCachedThreadPool中就是将核心线程数设置为0的。

maxPoolSize是线程池的最大线程数。这个最大线程数是对于或等于核心线程数的,当你用newFixedThreadPool和newSingleThreadPool时,核心线程数和最大线程数是相等的,这一点你可以在这两种线程池的构造函数中得到验证。

keepAliveTime是用来约束某种线程的生存时间的,这个某种线程是什么意思呢,当线程池所使用的线程数设为n,这个某种线程是一类线程,就是n-corePoolSize的线程,就是超过核心线程数的线程。当线程池所创建的线程数大于核心线程数时,此时会计算当前的这些线程中哪些线程是空闲的,当空闲时间超过这个设定的keepAliveTime时,该线程就会被回收。

unit就是时间单位

workQueue:工作队列,该队列是当核心线程数已经使用完了,之后提交的任务就将放入这个工作队列,尤其需要注意的是,只有当你用execute()方法提交的任务才会放在这个工作队列中。一般到队列满的时候,才会创建先的线程来执行任务,当然要保证线程池的所有线程数小于或等于最大线程数。

threadFactory:线程工厂用于创建线程的。有些需求可能需要自己创建的线程。

handler:是拒绝策略,也叫饱和策略,当线程池中的线程数达到maxPoolSize,并且workQueue(有界队列)已经满了,就需要采用饱和策略了,对于新提交的任务是直接拒绝还是怎么样,是在这边设置的。

      这边了解了底层创建线程池的参数,回过头来看看newFixedThreadPool是怎么创建线程池的:

    public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}

newFixedThreadPool是是有一个参数,就是线程数nThread。这个参数用于设置核心线程数和最大线程数,其中的工作队列是LinkedBlockingQueue,这个队列是链表实现的,也就是说该工作队列不会满,除非你限制他的长度。而且该线程池中的最大线程数就是核心线程数。

接着我们看看其他几个线程池的构造方式。

(2)newSingleThreadExecutor

看看构造函数,核心线程数和最大线程数都是1,生存时间0,也是LinkedBlockingQueue

public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}

(3)newCachedThreadPool

这边有两个构造函数,就是传入承诺书不一样,一个啥也没传,一个穿了线程工厂。最大线程数是Integer的最大值,核心线程数为0,线程最大空闲时间为60秒。工作队列是SynchronousQueue,这个queue是即是交付的,就是任务一到就创建线程去执行。整个工作机制如下:来一个任务就创建线程去执行,当然有空闲线程让这些空闲线程去执行,空闲线程有一个60s生存时间。

    public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}/*** Creates a thread pool that creates new threads as needed, but* will reuse previously constructed threads when they are* available, and uses the provided* ThreadFactory to create new threads when needed.* @param threadFactory the factory to use when creating new threads* @return the newly created thread pool* @throws NullPointerException if threadFactory is null*/public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(),threadFactory);}

(4)newScheuledThreadPool

   /*** Creates a thread pool that can schedule commands to run after a* given delay, or to execute periodically.* @param corePoolSize the number of threads to keep in the pool,* even if they are idle* @return a newly created scheduled thread pool* @throws IllegalArgumentException if {@code corePoolSize < 0}*/public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {return new ScheduledThreadPoolExecutor(corePoolSize);}/*** Creates a thread pool that can schedule commands to run after a* given delay, or to execute periodically.* @param corePoolSize the number of threads to keep in the pool,* even if they are idle* @param threadFactory the factory to use when the executor* creates a new thread* @return a newly created scheduled thread pool* @throws IllegalArgumentException if {@code corePoolSize < 0}* @throws NullPointerException if threadFactory is null*/public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) {return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);}

这个定时线程池底层使用了ScheuledThreadPoolExecytor类,那我们去看看这个类是怎么构造的

   /*** Creates a new {@code ScheduledThreadPoolExecutor} with the* given core pool size.** @param corePoolSize the number of threads to keep in the pool, even*        if they are idle, unless {@code allowCoreThreadTimeOut} is set* @throws IllegalArgumentException if {@code corePoolSize < 0}*/public ScheduledThreadPoolExecutor(int corePoolSize) {super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue());}

该类继承 extends ThreadPoolExecutor,所使用的参数就是线程池核心线程数,最大线程数是Integer的最大值,队列用了延迟队列,没有生存时间这一说法。

 

 

 

 

 

 

 

 

 

 

 

这篇关于java 线程池初步涉足的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1131508

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

Linux下进程的CPU配置与线程绑定过程

《Linux下进程的CPU配置与线程绑定过程》本文介绍Linux系统中基于进程和线程的CPU配置方法,通过taskset命令和pthread库调整亲和力,将进程/线程绑定到特定CPU核心以优化资源分配... 目录1 基于进程的CPU配置1.1 对CPU亲和力的配置1.2 绑定进程到指定CPU核上运行2 基于

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直