(十三)Executors(线程池)

2023-12-19 07:58
文章标签 线程 十三 executors

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

前言:通过之前的博客对多线程有了或多或少的了解,接触了ExecutorService后顺带地接触到了线程池,当时用的还是固定大小的线程池,其实线程池分好几种,现在正好梳理下基本功能及用法。


demo地址:点击打开链接


1.Executors的主要api

executors的主要创建线程池的api如下图所示,除了newWorkStealingPool之外其他的基本都见过,简单地描述下其他API的作用。

  • newFixedThreadPool
    创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。定长线程池的大小最好根据系统资源进行设置,如Runtime.getRuntime().availableProcessors()。
    创建方式: Executors.newFixedThreadPool();
  • newCachedThreadPool
    创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
    创建方式: Executors.newCachedThreadPool();
  • newSingleThreadExecutor
    创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
    创建方式: Executors.newSingleThreadExecutor ();
  • newScheduledThreadPool
    创建一个定长线程池,支持定时及周期性任务执行。
    创建方式: Executors.newScheduledThreadPool ()


2. 结合注释理解API

我还是比较喜欢看源码注释的,只要理解没问题那么正确性就有保证,网上的有可能会误导,并且有时候会看到平常没注意到的知识点,还是挺好的。我主要就源码注释翻译一下加进自己的理解。

2.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>());}

newFixedThreadPool创建一个复用固定数目线程的线程池,来执行一个共享的无界任务队列。在任何时候,最多n个线程在执行任务。如果所有线程都在忙的时候,有额外的任务被提交,那么那些被提交的任务会一直在队列中等待,知道有线程空闲。如果任何线程在调用shutdown之前由于失败而中断了,一个新的线程会取代它的位置。线程池里的线程会一直存活到调用shutdown。

在我看来这个固定大小的线程池就像一个有着固定工人数的工厂,反正只有这么多人,只能干这么多活,活多了就积压下来等有空了再干,如果有工人离职或生病啥的,再招一个代替。当然工厂倒闭了所有人就都得走了。但是我一直对线程复用很有疑问,线程是干完一件活还可以干第二件么,不是立刻干掉自己重新创建一个新的么,但看源码是可以接着干。


2.2 newSingleThreadExecutor

/*** Creates an Executor that uses a single worker thread operating* off an unbounded queue. (Note however that if this single* thread terminates due to a failure during execution prior to* shutdown, a new one will take its place if needed to execute* subsequent tasks.)  Tasks are guaranteed to execute* sequentially, and no more than one task will be active at any* given time. Unlike the otherwise equivalent* {@code newFixedThreadPool(1)} the returned executor is* guaranteed not to be reconfigurable to use additional threads.** @return the newly created single-threaded Executor*/public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}

简单看来就是把newFixedThreadPool后面参数换成了1,但是注释中最后强调了和newFixedThreadPool的不同在于这个newSingleThreadExecutor线程池保证不被配置使用额外的线程。感觉有点抽象,百度了下,链接如下:

点击打开链接

简单总结一下有两点:

1.屏蔽了ThreadPoolExecutor中暴露出来的API接口,比如setCorePoolSize,可以重新设置线程池大小,使单线程池没有后门。

1)newFixedThreadPool使用的是:

ThreadPoolExecutor-->AbstractExecutorService


2)newSingleThreadExecutor使用的是 :

FinalizableDelegatedExecutorService-->DelegatedExecutorService-->AbstractExecutorService


2.实质上是个装饰类,多了个gc时停掉线程池的功能。

private static class FinalizableDelegatedExecutorServiceextends DelegatedExecutorService {FinalizableDelegatedExecutorService(ExecutorService executor) {super(executor);}protected void finalize() {super.shutdown();}}


2.3 newCachedThreadPool

/*** Creates a thread pool that creates new threads as needed, but* will reuse previously constructed threads when they are* available.  These pools will typically improve the performance* of programs that execute many short-lived asynchronous tasks.* Calls to {@code execute} will reuse previously constructed* threads if available. If no existing thread is available, a new* thread will be created and added to the pool. Threads that have* not been used for sixty seconds are terminated and removed from* the cache. Thus, a pool that remains idle for long enough will* not consume any resources. Note that pools with similar* properties but different details (for example, timeout parameters)* may be created using {@link ThreadPoolExecutor} constructors.** @return the newly created thread pool*/public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}

创建一个随需要创建新线程的线程池,但是如果先前创建的线程可用则复用。这些线程池将改善那些执行短时间异步任务程序的性能。调用execute将重用先前创建好的可用线程。如果没有可用的线程存在,则一个新的线程会被创建并加入到线程池中去。已经未被使用即空闲了60s的线程将被中断并且从缓存中移除。因此,一个空闲时间足够长的线程池将是空的。

可以看到两点需要注意的:

1)适用于短耗时的异步任务,超过60s空闲会被中断的

2)这个线程池是会动态变化的,随着任务的多少进行线程池大小的变化


2.4  newScheduledThreadPool

  /*** 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);}

创建一个可延时或定时执行任务的线程池。


2.5 newWorkStealingPool

/*** Creates a thread pool that maintains enough threads to support* the given parallelism level, and may use multiple queues to* reduce contention. The parallelism level corresponds to the* maximum number of threads actively engaged in, or available to* engage in, task processing. The actual number of threads may* grow and shrink dynamically. A work-stealing pool makes no* guarantees about the order in which submitted tasks are* executed.** @param parallelism the targeted parallelism level* @return the newly created thread pool* @throws IllegalArgumentException if {@code parallelism <= 0}* @since 1.8*/public static ExecutorService newWorkStealingPool(int parallelism) {return new ForkJoinPool(parallelism,ForkJoinPool.defaultForkJoinWorkerThreadFactory,null, true);}

创建一个包含足够线程的线程池,并且使用足够多的队列来减少竞争。并发的等级对应于加入的最大线程数。事实上线程数也许会动态增减。一个work-stealing的线程池不保证执行的任务是有序的。


3. newScheduledThreadPool用法

感觉其他的线程池内部封装的比较好,用法应该差不多,当ExecutorService用就好了,ScheduledThreadPoolExecutor会特殊一点,就用这个写个demo熟悉一下。

看了下主要接口是如下两个:

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit) 

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit)

demo如下:

package com.example.demo_12_executors;import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;public class MainActivity extends AppCompatActivity {private static final String TAG = "executorsTest";ScheduledExecutorService executorService;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);executorService = Executors.newScheduledThreadPool(5);executorService.scheduleWithFixedDelay(new Runnable() {@Overridepublic void run() {Log.d(TAG, "this is sheduledExecutorService");try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}},1000, 2000, TimeUnit.MILLISECONDS);}@Overrideprotected void onDestroy() {super.onDestroy();executorService.shutdown();}
}


结果:

1.scheduleAtFixedRate表明是从任务开始算间隔的,如果任务执行时间多余间隔,则间隔无效,等上一个任务执行完下一个任务立刻执行。


2.scheduleWithFixedDelay表明是从上一个任务结束开始算的。


4. ThreadPoolExecutor各入参的意义

/*** 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) {if (corePoolSize < 0 ||maximumPoolSize <= 0 ||maximumPoolSize < corePoolSize ||keepAliveTime < 0)throw new IllegalArgumentException();if (workQueue == null || threadFactory == null || handler == null)throw new NullPointerException();this.corePoolSize = corePoolSize;this.maximumPoolSize = maximumPoolSize;this.workQueue = workQueue;this.keepAliveTime = unit.toNanos(keepAliveTime);this.threadFactory = threadFactory;this.handler = handler;}
  • corePoolSize:核心池的大小,这个参数跟后面讲述的线程池的实现原理有非常大的关系。在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务,除非调用了prestartAllCoreThreads()或者prestartCoreThread()方法,从这2个方法的名字就可以看出,是预创建线程的意思,即在没有任务到来之前就创建corePoolSize个线程或者一个线程。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
  • maximumPoolSize:线程池最大线程数,这个参数也是一个非常重要的参数,它表示在线程池中最多能创建多少个线程;
  • keepAliveTime:表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize,即当线程池中的线程数大于corePoolSize时,如果一个线程空闲的时间达到keepAliveTime,则会终止,直到线程池中的线程数不超过corePoolSize。但是如果调用了allowCoreThreadTimeOut(boolean)方法,在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0;
  • unit:参数keepAliveTime的时间单位,有7种取值。TimeUnit.DAYS、TimeUnit.HOURS、TimeUnit.MINUTES、TimeUnit.SECONDS、TimeUnit.MILLISECONDS、TimeUnit.MICROSECONDS、TimeUnit.NANOSECONDS
  • workQueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择:ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue。
    ArrayBlockingQueue和PriorityBlockingQueue使用较少,一般使用LinkedBlockingQueue和Synchronous。线程池的排队策略与BlockingQueue有关。
  • threadFactory:线程工厂,主要用来创建线程;
  • handler:表示当拒绝处理任务时的策略,有以下四种取值:
    ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
    ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
    ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
    ThreadPoolExecutor.CallerRunsPolicy:由调用线程处理该任务
那么poolSize、corePoolSize、maximumPoolSize三者的关系是如何的呢?
当新提交一个任务时:
(1)如果poolSize<corePoolSize,新增加一个线程处理新的任务。
(2)如果poolSize=corePoolSize,新任务会被放入阻塞队列等待。
(3)如果阻塞队列的容量达到上限,且这时poolSize<maximumPoolSize,新增线程来处理任务。
(4)如果阻塞队列满了,且poolSize=maximumPoolSize,那么线程池已经达到极限,会根据饱和策略RejectedExecutionHandler拒绝新的任务。


所以通过上面的描述可知corePoolSize<=maximumPoolSize,poolSize<=maximumPoolSize;而poolSize和corePoolSize无法比较,poolSize是有可能比corePoolSize大的。


5. 总结

简单地从功能上了解了下各个线程池的作用,主要有四个,分别是固定、缓存、单个、定时线程池,对于固定线程池和定时线程池的大小其实还是要根据当前任务情况以及硬件情况综合考虑以便能充分利用CPU性能。

遵循两原则:
1、如果是CPU密集型任务,就需要尽量压榨CPU,参考值可以设为 NCPU+1
2、如果是IO密集型任务,参考值可以设置为2*NCPU
当然,这只是一个参考值,具体的设置还需要根据实际情况进行调整,比如可以先将线程池大小设置为参考值,再观察任务运行情况和系统负载、资源利用率来进行适当调整。

这篇关于(十三)Executors(线程池)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java多线程父线程向子线程传值问题及解决

《Java多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH

java父子线程之间实现共享传递数据

《java父子线程之间实现共享传递数据》本文介绍了Java中父子线程间共享传递数据的几种方法,包括ThreadLocal变量、并发集合和内存队列或消息队列,并提醒注意并发安全问题... 目录通过 ThreadLocal 变量共享数据通过并发集合共享数据通过内存队列或消息队列共享数据注意并发安全问题总结在 J

异步线程traceId如何实现传递

《异步线程traceId如何实现传递》文章介绍了如何在异步请求中传递traceId,通过重写ThreadPoolTaskExecutor的方法和实现TaskDecorator接口来增强线程池,确保异步... 目录前言重写ThreadPoolTaskExecutor中方法线程池增强总结前言在日常问题排查中,

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

C语言线程池的常见实现方式详解

《C语言线程池的常见实现方式详解》本文介绍了如何使用C语言实现一个基本的线程池,线程池的实现包括工作线程、任务队列、任务调度、线程池的初始化、任务添加、销毁等步骤,感兴趣的朋友跟随小编一起看看吧... 目录1. 线程池的基本结构2. 线程池的实现步骤3. 线程池的核心数据结构4. 线程池的详细实现4.1 初

Java子线程无法获取Attributes的解决方法(最新推荐)

《Java子线程无法获取Attributes的解决方法(最新推荐)》在Java多线程编程中,子线程无法直接获取主线程设置的Attributes是一个常见问题,本文探讨了这一问题的原因,并提供了两种解决... 目录一、问题原因二、解决方案1. 直接传递数据2. 使用ThreadLocal(适用于线程独立数据)

线程的四种操作

所属专栏:Java学习        1. 线程的开启 start和run的区别: run:描述了线程要执行的任务,也可以称为线程的入口 start:调用系统函数,真正的在系统内核中创建线程(创建PCB,加入到链表中),此处的start会根据不同的系统,分别调用不同的api,创建好之后的线程,再单独去执行run(所以说,start的本质是调用系统api,系统的api

java线程深度解析(六)——线程池技术

http://blog.csdn.net/Daybreak1209/article/details/51382604 一种最为简单的线程创建和回收的方法: [html]  view plain copy new Thread(new Runnable(){                @Override               public voi

java线程深度解析(五)——并发模型(生产者-消费者)

http://blog.csdn.net/Daybreak1209/article/details/51378055 三、生产者-消费者模式     在经典的多线程模式中,生产者-消费者为多线程间协作提供了良好的解决方案。基本原理是两类线程,即若干个生产者和若干个消费者,生产者负责提交用户请求任务(到内存缓冲区),消费者线程负责处理任务(从内存缓冲区中取任务进行处理),两类线程之

java线程深度解析(四)——并发模型(Master-Worker)

http://blog.csdn.net/daybreak1209/article/details/51372929 二、Master-worker ——分而治之      Master-worker常用的并行模式之一,核心思想是由两个进程协作工作,master负责接收和分配任务,worker负责处理任务,并把处理结果返回给Master进程,由Master进行汇总,返回给客