java并发初探ThreadPoolExecutor拒绝策略

ThreadPoolExecuter构造器

corePoolSize是核心线程池,就是常驻线程池数量;
maximumPoolSize是最大线程池数量,如果队列满了,就会创建新的线程任务。如果与corePoolSize一样大小,
那么就是固定大小的鹅线程池;
keepAliveTime表示线程池中线程空闲时间,当空闲时间达到keepAliveTime,线程会被销毁,直到剩下corePoolSize,
默认情况只有当前的线程数大于corePoolSize时keepAliveTime才会起作用;
unit时间单位;
BlockingQueue阻塞队列。当请求线程数大于corePoolSize时,线程会进入阻塞队列,当达到阻塞队列的上限是,线程池会创建新的
线程池,最大的线程数就是maximumPoolSize;
其他参数:
threadFactory线程工厂,默认是Executors.defaultThreadFactory();
RejectedExecutionHandler拒绝策略的执行对象,当线程池数量大于maximumPoolSize,拒绝策略就会执行;

    /*** Creates a new {@code ThreadPoolExecutor} with the given initial* parameters and default thread factory and rejected execution handler.* It may be more convenient to use one of the {@link Executors} factory* methods instead of this general purpose constructor.** @param corePoolSize the number of threads to keep in the pool, even*        if they are idle, unless {@code allowCoreThreadTimeOut} is set* @param maximumPoolSize the maximum number of threads to allow in the*        pool* @param 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.* @param unit the time unit for the {@code keepAliveTime} argument* @param workQueue the queue to use for holding tasks before they are*        executed.  This queue will hold only the {@code Runnable}*        tasks submitted by the {@code execute} method.* @throws IllegalArgumentException if one of the following holds:<br>*         {@code corePoolSize < 0}<br>*         {@code keepAliveTime < 0}<br>*         {@code maximumPoolSize <= 0}<br>*         {@code maximumPoolSize < corePoolSize}* @throws NullPointerException if {@code workQueue} is null*/public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);}

拒绝策略

AbortPolicy
默认拒绝策略,丢弃任务,抛出异常RejectedExecutionException

DiscardPolicy
丢弃任务
DiscardOldestPolicy
把最旧的等待任务抛弃,放入等待队列

CallerRunsPolicy
拒绝任务在当前正在执行的线程运行

    /*** A handler for rejected tasks that throws a* {@code RejectedExecutionException}.*/public static class AbortPolicy implements RejectedExecutionHandler/*** A handler for rejected tasks that silently discards the* rejected task.*/public static class DiscardPolicy implements RejectedExecutionHandler/*** A handler for rejected tasks that discards the oldest unhandled* request and then retries {@code execute}, unless the executor* is shut down, in which case the task is discarded.*/public static class DiscardOldestPolicy implements RejectedExecutionHandler/*** A handler for rejected tasks that runs the rejected task* directly in the calling thread of the {@code execute} method,* unless the executor has been shut down, in which case the task* is discarded.*/public static class CallerRunsPolicy implements RejectedExecutionHandler     

例子

package com.java.javabase.thread.base.threadpool;import lombok.extern.slf4j.Slf4j;import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;/*** @author*/
@Slf4j
public class ThreadPoolAbortPolicyTest {public static void main(String[] args) {ThreadPoolExecutor pool =new ThreadPoolExecutor(1,2,0, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(1));//pool.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());//pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());//pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());pool.execute(() -> log.info("thread {} 0", Thread.currentThread().getName()));pool.execute(() -> log.info("thread {} 1", Thread.currentThread().getName()));pool.execute(() -> log.info("thread {} 2", Thread.currentThread().getName()));pool.execute(() -> log.info("thread {} 3", Thread.currentThread().getName()));pool.execute(() -> log.info("thread {} 4", Thread.currentThread().getName()));pool.shutdown();}
}

DiscardOldestPolicy结果

2019-08-14 15:56:18,972   [pool-1-thread-1] INFO  ThreadPoolAbortPolicyTest  - thread pool-1-thread-1 0
2019-08-14 15:56:18,972   [pool-1-thread-1] INFO  ThreadPoolAbortPolicyTest  - thread pool-1-thread-1 4
2019-08-14 15:56:18,972   [pool-1-thread-2] INFO  ThreadPoolAbortPolicyTest  - thread pool-1-thread-2 2

CallerRunsPolicy结果

2019-08-14 15:58:03,439   [pool-1-thread-1] INFO  ThreadPoolAbortPolicyTest  - thread pool-1-thread-1 0
2019-08-14 15:58:03,439   [pool-1-thread-2] INFO  ThreadPoolAbortPolicyTest  - thread pool-1-thread-2 2
2019-08-14 15:58:03,454   [pool-1-thread-1] INFO  ThreadPoolAbortPolicyTest  - thread pool-1-thread-1 1
2019-08-14 15:58:03,439   [main] INFO  ThreadPoolAbortPolicyTest  - thread main 3
2019-08-14 15:58:03,454   [pool-1-thread-1] INFO  ThreadPoolAbortPolicyTest  - thread pool-1-thread-1 4

转载于:https://www.cnblogs.com/JuncaiF/p/11352571.html

java并发初探ThreadPoolExecutor拒绝策略相关推荐

  1. java并发初探ConcurrentSkipListMap

    java并发初探ConcurrentSkipListMap ConcurrentSkipListMap以调表这种数据结构以空间换时间获得效率,通过volatile和CAS操作保证线程安全,而且它保证了 ...

  2. java并发初探ConcurrentHashMap

    java并发初探ConcurrentHashMap Doug Lea在java并发上创造了不可磨灭的功劳,ConcurrentHashMap体现这位大师的非凡能力. 1.8中ConcurrentHas ...

  3. java并发初探CyclicBarrier

    java并发初探CyclicBarrier CyclicBarrier的作用 CyclicBarrier,"循环屏障"的作用就是一系列的线程等待直至达到屏障的"瓶颈点&q ...

  4. java并发初探CountDownLatch

    java并发初探CountDownLatch CountDownLatch是同步工具类能够允许一个或者多个线程等待直到其他线程完成操作. 当前前程A调用CountDownLatch的await方法进入 ...

  5. java并发初探ReentrantWriteReadLock

    java并发初探ReentrantWriteReadLock ReenWriteReadLock类的优秀博客 ReentrantReadWriteLock读写锁详解 Java多线程系列--" ...

  6. Java线程池的拒绝策略

    一.简介 jdk1.5 版本新增了JUC并发编程包,极大的简化了传统的多线程开发.前面文章中介绍了线程池的使用,链接地址:https://www.cnblogs.com/eric-fang/p/900 ...

  7. Java 并发编程 --- ThreadPoolExecutor(五)

    使用线程池的好处 引用自 http://ifeve.com/java-threadpool/ 的说明: 降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 提高响应速度.当任务到达时 ...

  8. 一文详解java线程池 详解Java线程池的七个参数 详解池化技术 java如何选择核心线程数 详解Java线程池的拒绝策略

    目录 引言 线程池使用场景 加快请求响应(响应时间优先) 加快处理大任务(吞吐量优先) 特殊说明 线程池的池化技术 线程池的创建 手动创建 创建newFixedThreadPool线程池 创建newS ...

  9. Java中线程池拒绝策略——代码讲解

    1.在使用ThreadPoolExecutor创建多线程时候,需要出入多个参数,如下: public ThreadPoolExecutor(int corePoolSize,              ...

最新文章

  1. 原型模式(Prototype)
  2. JAVA生成不重复随机数算法
  3. eclipse中查看java源代码设置方法
  4. 使用PHP对数据库输入进行恶意代码清除
  5. 如何在JavaScript中将字符串转换为布尔值?
  6. Effective java -- 2 对于所有对象都通用到方法
  7. echart中拆线点的偏移_Qt中圆弧和扇形的绘制
  8. linux下mkdir头文件_Linux中mkdir函数与Windows中_mkdir函数的区别
  9. TypeSDK免费手游多渠道SDK接入方案
  10. python符号表_根据第一个字符分割列表-Python
  11. windows之bat之批处理复制文件
  12. [LeetCode] One Edit Distance 一个编辑距离
  13. sniffer辅助功能详解
  14. NumPy的详细教程(官网手册翻译)
  15. 向量交点坐标公式_高中数学必修1-5常用公式(定理)
  16. HFSS天线设计笔记-------主极化与交叉极化
  17. C#调用Qpdf的界面+拖拽pdf文件到窗口+解除pdf权限密码+另存为
  18. Javaweb重要知识点总结(六)常见的前端框架
  19. 老服务器上安装windows server 2016
  20. SAP ABAP 配置表开发常见问题总结与开发指南(SM30 SM34 SE54)

热门文章

  1. Python“文件操作”Excel篇(上)
  2. .net问题记录及解决方法
  3. java和js实现电话号码部分隐藏
  4. Redis命令小细节
  5. 编译hibernate源代码
  6. AJAX无刷新搜索,即输即得(未完善…)
  7. Linux内存管理(一)——从硬件角度看内存管理
  8. (75)Verilog HDL系统函数和任务:$readmemh
  9. FPGA RAM时分复用减少逻辑资源
  10. linux vg划分目录,修改根目录所在VG名称