java线程池快速创建_java 并发包里Eexcutors创建线程池的几种方法

Executors

Executors提供了一些方便创建TreadPoolExecutors的方法,主要有以下几个:

newFixedThreadPool(int)

创建一个固定大小线程池。从下面的代码我们可以看出,corePoolSize需要指定,即即使空闲没有任务执行也一直启动的线程,newFixedThreadPool把ThreadPoolExecutor中的keepAliveTime设置为0,即ThreadPoolExecutor中启动的线程数量启动后就一直运行,并不会由于在keepAliveTime的时间内仍没有任务执行而退出。缓冲任务的队列使用的是LinkedBlockingQueue,如果放入线程池中的任务数量(最大为整数的最大值)比线程池中的线程多时,则会把多余的任务放到队列里。

public static ExecutorService newFixedThreadPool(int nThreads) {

return new ThreadPoolExecutor(nThreads, nThreads,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue());

}

newSingleThreadExecutor()

相当于创建了只有一个线程的固定大小线程池,使用此线程池的时候,并行执行的任务只有一个,其他的任务都放到LinkedBlockingQueue队列中

public static ExecutorService newSingleThreadExecutor() {

return new FinalizableDelegatedExecutorService

(new ThreadPoolExecutor(1, 1,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue()));

}

newCachedThreadPool()

创建一个带缓存的线程池,从下面代码可以看出,newCachedThreadPool把ThreadPoolExecutor中的corePoolSize设置为0,即不允许有空闲的线程,最大线程数量为整数的最大值,线程的keepAliveTime为60秒,即如果60秒这个线程还没有任务执行,则退出。缓存任务的队列为SynchronousQueue,在使用时,放入newCachedThreadPool的任务都会复用线程或者启动新线程来执行,随着放入的任务的数量的增加,newCachedThreadPool中新启动的线程数量也随之增加,直到整数的最大值,则抛出异常。

public static ExecutorService newCachedThreadPool() {

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

60L, TimeUnit.SECONDS,

new SynchronousQueue());

}

newScheduledThreadPool(int)

创建一个定时线程池,其中corePoolSize(即使空闲也不会退出的线程数量)需要指定,最大线程数量为整数的最大值,线程的keepAliveTime为0,即不设置线程的空闲时间,缓存任务的队列为DelayedWorkQueue,即任务数量超过线程池中的线程数量,则把任务放到DelayedWorkQueue队列里缓存。在实际业务中,通常会有一些需要定时或者延迟执行的任务,此时,newScheduledThreadPool是个不错的选择。当然在jdk5前可以用Timer来实现,但是Timer只能单线程。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {

return new ScheduledThreadPoolExecutor(corePoolSize);

}

public ScheduledThreadPoolExecutor(int corePoolSize) {

super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,

new DelayedWorkQueue());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值