如何设置线程池的常规变量

Parameters:
  
 corePoolSize - the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set.
 (If the number of threads to keep in the pool less than corePoolSize,the pool will create new thread instead of threads to keep to deal the job.)
  
  
 maximumPoolSize - the maximum number of threads to allow in the pool
 (When workQueue is full and the number of threads to keep in the pool more than corePoolSize,the pool will create new Threads until the number equals maximunPoolSize.If the number of threads to keep more than maximumPoolSize,the pool will throw the exception.)
  
  
 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.
 (if allowCoreThreadTimeOut is true,all of the threads will be kill)
  
 unit - the time unit for the keepAliveTime argument
  
 workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
  
  
 threadFactory - the factory to use when the executor creates a new thread
  
 forExample:
 tasks,每秒需要处理的最大任务数量
 tasktime,处理第个任务所需要的时间
 responsetime,系统允许任务最大的响应时间,比如每个任务的响应时间不得超过2秒。
  
 corePoolSize:
  
 每个任务需要tasktime秒处理,则每个线程每钞可处理1/tasktime个任务。系统每秒有tasks个任务需要处理,则需要的线程数为:tasks/(1/tasktime),即tasks*tasktime个线程数。假设系统每秒任务数为100~1000,每个任务耗时0.1秒,则需要100*0.1至1000*0.1,即10~100个线程。那么corePoolSize应该设置为大于10,具体数字最好根据8020原则,即80%情况下系统每秒任务数,若系统80%的情况下第秒任务数小于200,最多时为1000,则corePoolSize可设置为20。
  
 queueCapacity:
  
 任务队列的长度要根据核心线程数,以及系统对任务响应时间的要求有关。队列长度可以设置为(corePoolSize/tasktime)*responsetime: (20/0.1)*2=400,即队列长度可设置为400。
 队列长度设置过大,会导致任务响应时间过长,切忌以下写法:
  
 LinkedBlockingQueue queue = new LinkedBlockingQueue();
  
 这实际上是将队列长度设置为Integer.MAX_VALUE,将会导致线程数量永远为corePoolSize,再也不会增加,当任务数量陡增时,任务响应时间也将随之陡增。
  
 maxPoolSize:
  
 当系统负载达到最大值时,核心线程数已无法按时处理完所有任务,这时就需要增加线程。每秒200个任务需要20个线程,那么当每秒达到1000个任务时,则需要(1000-queueCapacity)*(20/200),即60个线程,可将maxPoolSize设置为60。
  
  
  
 keepAliveTime:
  
 线程数量只增加不减少也不行。当负载降低时,可减少线程数量,如果一个线程空闲时间达到keepAliveTiime,该线程就退出。默认情况下线程池最少会保持corePoolSize个线程。
  
  
  
 allowCoreThreadTimeout:
  
 默认情况下核心线程不会退出,可通过将该参数设置为true,让核心线程也退出。
  
  
  
 以上关于线程数量的计算并没有考虑CPU的情况。若结合CPU的情况,比如,当线程数量达到50时,CPU达到100%,则将maxPoolSize设置为60也不合适,此时若系统负载长时间维持在每秒1000个任务,则超出线程池处理能力,应设法降低每个任务的处理时间(tasktime)。
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值