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

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2