线程池(二):java自定义线程池ThreadPoolExecutor

上一篇博文有说到四种常见的线程池,但是无论创建哪一种线程池必须要调用ThreadPoolExecutor这个类,线程池类为 java.util.concurrent.ThreadPoolExecutor,其关系为:

既然我们都调用了ThreadPoolExecutor这个类,那么我们来详细解析一下这个类。

ThreadPoolExecutor

这个类的构造方法有六个参数:

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, 
RejectedExecutionHandler handler) 

分别为:

corePoolSize: 线程池维护线程的最少数量 
maximumPoolSize:线程池维护线程的最大数量 
keepAliveTime: 线程池维护线程所允许的空闲时间 
unit: 线程池维护线程所允许的空闲时间的单位 
workQueue: 线程池所使用的缓冲队列 
handler: 线程池对拒绝任务的处理策略 

使用方式:

ExecutorService executorService = new ThreadPoolExecutor(2, 2, 
            5, TimeUnit.SECONDS, 
            new ArrayBlockingQueue<>(512), 
            new ThreadPoolExecutor.DiscardPolicy());

如上写法相当于

ExecutorService fixed = Executors.newFixedThreadPool(2);

这个构造方法对于队列是什么类型比较关键。

缓冲队列

在使用有界队列时,若有新的任务需要执行,如果线程池实际线程数小于corePoolSize,则优先创建线程,
若大于corePoolSize,则会将任务加入队列,
若队列已满,则在总线程数不大于maximumPoolSize的前提下,创建新的线程,
若队列已经满了且线程数大于maximumPoolSize,则执行拒绝策略。或其他自定义方式。

常用的几种队列

(1)ArrayBlockingQueue:规定大小的BlockingQueue,其构造必须指定大小。其所含的对象是FIFO顺序排序的。

(2)LinkedBlockingQueue:大小不固定的BlockingQueue,若其构造时指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE来决定。其所含的对象是FIFO顺序排序的。

(3)PriorityBlockingQueue:类似于LinkedBlockingQueue,但是其所含对象的排序不是FIFO,而是依据对象的自然顺序或者构造函数的Comparator决定。

(4)SynchronizedQueue:特殊的BlockingQueue,对其的操作必须是放和取交替完成。

 

队列有界性数据结构
ArrayBlockingQueuebounded(有界)加锁arrayList
LinkedBlockingQueueoptionally-bounded加锁linkedList
PriorityBlockingQueueunbounded加锁heap
DelayQueueunbounded加锁heap
SynchronousQueuebounded加锁
LinkedTransferQueueunbounded加锁heap
LinkedBlockingDequeunbounded无锁heap

拒绝策略

分类

特点
AbortPolicy直接抛出异常,阻止应用正常工作。(默认使用该策略)
CallerRunsPolicy不会真正丢弃任务,当线程池未关闭,该策略直接在调用者线程中运行当前丢弃任务。
DiscardPolicy丢弃无法处理的任务,不做任何处理。
DiscardOldestPolicy丢弃最老的任务,也就是即将执行的任务,并尝试提交当前任务。

 以DiscardOldestPolicy拒绝策略为例:

	ExecutorService executorService = new ThreadPoolExecutor(3, 4, 
            1, TimeUnit.SECONDS, 
            new ArrayBlockingQueue<>(5), 
            new ThreadPoolExecutor.DiscardOldestPolicy());// 指定拒绝策略
	for (int i = 0; i < 10; i++) {
		final int index = i;
		executorService.execute(new Runnable() {
		
			@Override
			public void run() {
				System.out.println("第"+Thread.currentThread().getName()+"个线程执行第"+index+"个任务,时间:"+new Date().getSeconds());
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}
	executorService.shutdown();
}

 结果看发现第三个任务被第八个任务顶掉了:

第pool-1-thread-2个线程执行第1个任务,时间:27
第pool-1-thread-1个线程执行第0个任务,时间:27
第pool-1-thread-4个线程执行第8个任务,时间:27
第pool-1-thread-3个线程执行第2个任务,时间:27
第pool-1-thread-4个线程执行第4个任务,时间:37
第pool-1-thread-2个线程执行第5个任务,时间:37
第pool-1-thread-3个线程执行第6个任务,时间:37
第pool-1-thread-1个线程执行第7个任务,时间:37
第pool-1-thread-2个线程执行第9个任务,时间:47

代码中executorService.execute为执行线程池,那么最后看一下该方法的源码:

 public void execute(Runnable command) {  
          if (command == null) //不能是空任务  
              throw new NullPointerException();  
      //如果还没有达到corePoolSize,则添加新线程来执行任务  
          if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {  
           //如果已经达到corePoolSize,则不断的向工作队列中添加任务  
              if (runState == RUNNING && workQueue.offer(command)) {  
              //线程池已经没有任务  
                  if (runState != RUNNING || poolSize == 0)   
                      ensureQueuedTaskHandled(command);  
              }  
           //如果线程池不处于运行中或者工作队列已经满了,但是当前的线程数量还小于允许最大的maximumPoolSize线程数量,则继续创建线程来执行任务  
              else if (!addIfUnderMaximumPoolSize(command))  
              //已达到最大线程数量,任务队列也已经满了,则调用饱和策略执行处理器  
                  reject(command); // is shutdown or saturated  
          }  
  }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值