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 WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原