线程池
首先,让我们来看看一般的线程池生成器公共资源定位器(Intcorepoolsize,
int最大轮询率,
长期保持时间,
时间单元,
封锁队列可以使用的工作队列,
电信网电信网、
rejectedexecutionhandlerhandler ) {
//内容省略
.
{1}参数的含义如下。
corePoolSize (核心线程池的大小,核心线程优先执行任务的maximumPoolSize )线程池的最大容量,即线程池的并发最大线程数keepAliveTime )生存时间、 核心线程以外为空闲)核心线程=线程池内的最大线程池-核心线程)后,放弃unit多久:与上述生存时间对应的时间单位workQueue :工作队列(阻塞队列)为线程空闲后用于获取任务的threadFactory )线程工厂是用于使用工厂模式创建线程的handler )拒绝策略,在上述阻塞队列已满之后
让我们看看
为什么阿里巴巴规约不建议使用Executors创建线程池?
JDK提供的典型线程池executors.newsinglethreadexecutor (; //创建单核线程池
executors.newscheduledthreadpool (10; //创建按计划执行的线程池
executors.newcachedthreadpool (//创建自动增长的线程池
executors.newfixedthreadpool(4; //为固定线程数的线程池
SingleThreadExecutor线程池
executors.newsinglethreadexecutor ()创建源代码publicstaticexecutorservicenewsinglethreadexecutor {
returnnewfinalizabledelegatedexecutorservice
(newthreadpoolexecutor (1,1,
0L,time单元. milliseconds,
new LinkedBlockingQueueRunnable () );
您将看到您正在使用ThreadPoolExecutor,并且正在使用工作队列LinkedBlockingQueue。 LinkedBlockingQueue是一个无边界队列。
虽然LinkedBlockingQueue实际上也是有界队列,但队列长度为Integer.MAX_VALUE,其下有LinkedBlockingQueue的构造函数。
公共链接模块队列(
this (整数.最大值;
在上一篇文章中,我们讨论了线程池的工作流,如下图所示
因此,SingleThreadExecutor线程池使用了无边界队列。 任务持续发生,执行不及时时,继续进入工作队列(阻塞队列)。 如果没有边界,最终会导致OOM,因此不推荐使用
ScheduledThreadPool线程池
executors.newscheduledthreadpool (10 )的源代码如下所示publicscheduledthreadpoolexecutor (Intcorepoolsize )。
super (公司,Integer.MAX_VALUE,0,纳米符号,
新延迟的工作队列();
}综上所述,我们发现无边界队列可能会导致OOM,因此我们直接分析了延迟工作队列是否为无边界队列。
源代码包括以下内容:
私有身份证明_容量=16;
私有运行时间安排? 库尤=
新的运行时间表? [INITIAL_CAPACITY]其实DelayedWorkQueue采用数组实现,初始容量为16,因此是有界队列。
DelayedWorkQueue是有界队列,但线程的最大数设置在Integer.MAX_VALUE、CachedThreadPool线程池中,因此在块队列已满之后打开最大线程,然后选择
CachedThreadPool线程池
executors.newcachedthreadpool (publicstaticexecutorservicenewcachedthreadpool (
returnnewthreadpoolexecutor(0,Integer.MAX_VALUE,
60L,time单元. seconds,
新同步usqueuerunnable ();
与ScheduledThreadPool线程池一样,同步队列不是无边界队列,但在同步队列内部只包含一个元素的队列。 阻止将元素插入队列的线程,直到另一个线程从队列中获取队列中的元素。 )的最大线程池数设置为Integer.MAX_VALUE时,可能会发生OOM异常。
FixedThreadPool线程池
executors.newfixedthreadpool (4)的源代码如下所示publicstaticexecutorservicenewfixedthreadpool {
returnnewthreadpoolexecutor (Nthreads,nthreads,
0L,time单元. milliseconds,
new LinkedBlockingQueueRunnable ();
与SingleThreadExecutor线程池一样,LinkedBlockingQueue是无边界队列,容易发生OOM异常。
如在