ThreadPoolExcutor用法详解

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ThreadPoolExcutor用法详解相关的知识,希望对你有一定的参考价值。

参考技术A java线程池用法举例:

1、ThreadPoolExecutor executor =new ThreadPoolExecutor(2,10,30, TimeUnit.SECONDS,new ArrayBlockingQueue<>(100));

2、ThreadPoolExecutor executor2 =new ThreadPoolExecutor(2,10,30, TimeUnit.SECONDS,new LinkedBlockingDeque<>());

知道了各个参数的作用后,我们开始构造符合我们期待的线程池。首先看JDK给我们预定义的几种线程池:

一、预定义线程池

FixedThreadPool

publicstaticExecutorServicenewFixedThreadPool(intnThreads)returnnewThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,newLinkedBlockingQueue());   

corePoolSize与maximumPoolSize相等,即其线程全为核心线程,是一个固定大小的线程池,是其优势;

keepAliveTime = 0 该参数默认对核心线程无效,而FixedThreadPool全部为核心线程;

workQueue 为LinkedBlockingQueue(无界阻塞队列),队列最大值为Integer.MAX_VALUE。如果任务提交速度持续大余任务处理速度,会造成队列大量阻塞。因为队列很大,很有可能在拒绝策略前,内存溢出。是其劣势;

FixedThreadPool的任务执行是无序的;

适用场景:可用于Web服务瞬时削峰,但需注意长时间持续高峰情况造成的队列阻塞。

CachedThreadPool

publicstaticExecutorServicenewCachedThreadPool()returnnewThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,newSynchronousQueue());   

corePoolSize = 0,maximumPoolSize = Integer.MAX_VALUE,即线程数量几乎无限制;

keepAliveTime = 60s,线程空闲60s后自动结束。

workQueue 为 SynchronousQueue 同步队列,这个队列类似于一个接力棒,入队出队必须同时传递,因为CachedThreadPool线程创建无限制,不会有队列等待,所以使用SynchronousQueue;

适用场景:快速处理大量耗时较短的任务,如Netty的NIO接受请求时,可使用CachedThreadPool。

SingleThreadExecutor

publicstaticExecutorServicenewSingleThreadExecutor()returnnewFinalizableDelegatedExecutorService            (newThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS,newLinkedBlockingQueue()));   

咋一瞅,不就是newFixedThreadPool(1)吗?定眼一看,这里多了一层FinalizableDelegatedExecutorService包装,这一层有什么用呢,写个dome来解释一下:

publicstaticvoidmain(String[] args)        ExecutorService fixedExecutorService = Executors.newFixedThreadPool(1);        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) fixedExecutorService;        System.out.println(threadPoolExecutor.getMaximumPoolSize());        threadPoolExecutor.setCorePoolSize(8);                ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();//      运行时异常 java.lang.ClassCastException//      ThreadPoolExecutor threadPoolExecutor2 = (ThreadPoolExecutor) singleExecutorService;

对比可以看出,FixedThreadPool可以向下转型为ThreadPoolExecutor,并对其线程池进行配置,而SingleThreadExecutor被包装后,无法成功向下转型。 因此,SingleThreadExecutor被定以后,无法修改,做到了真正的Single。

ScheduledThreadPool

publicstaticScheduledExecutorServicenewScheduledThreadPool(intcorePoolSize)returnnewScheduledThreadPoolExecutor(corePoolSize);   

newScheduledThreadPool调用的是ScheduledThreadPoolExecutor的构造方法,而ScheduledThreadPoolExecutor继承了ThreadPoolExecutor,构造是还是调用了其父类的构造方法。

publicScheduledThreadPoolExecutor(intcorePoolSize)super(corePoolSize, Integer.MAX_VALUE,0, NANOSECONDS,newDelayedWorkQueue());   

二、自定义线程池

以上是关于ThreadPoolExcutor用法详解的主要内容,如果未能解决你的问题,请参考以下文章

HttpURLConnection 用法详解

linux 详解useradd 命令基本用法

ASP中FormatDateTime函数用法详解

Promise用法详解

Vue中watch用法详解

c++中vector的用法详解