ThreadPoolExecutor类实现了ExecutorService接口和Executor接口,可以设置线程池corePoolSize,最大线程池大小,AliveTime,拒绝策略等。常用构造方法:

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,

long keepAliveTime, TimeUnit unit,

BlockingQueue<Runnable> workQueue,

RejectedExecutionHandler handler)

corePoolSize: 线程池维护线程的最少数量

maximumPoolSize:线程池维护线程的最大数量

keepAliveTime: 线程池维护线程所允许的空闲时间

unit: 线程池维护线程所允许的空闲时间的单位

workQueue: 线程池所使用的缓冲队列

handler: 线程池对拒绝任务的处理策略

当一个任务通过execute(Runnable)方法欲添加到线程池时:

l  如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。

2  如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列。

3  如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。

4  如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。也就是:处理任务的优先级为:核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。

当线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。

handler有四个选择:

ThreadPoolExecutor.AbortPolicy()

抛出java.util.concurrent.RejectedExecutionException异常 ,示例如下:

private static class Worker implements Runnable {

public void run() {

System.out.println(Thread.currentThread().getName() + " is running");

}

}

public static void main(String[] args) {

int corePoolSize = 5;

int maxPoolSize = 10;

long keepAliveTime = 5;

BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(10);

//拒绝策略1:将抛出 RejectedExecutionException.

RejectedExecutionHandler handler =

new ThreadPoolExecutor.AbortPolicy();

ThreadPoolExecutor executor = new ThreadPoolExecutor

(corePoolSize, maxPoolSize,

keepAliveTime, TimeUnit.SECONDS,

queue, handler);

for(int i=0; i<100; i++) {

executor.execute(new Worker());

}

executor.shutdown();

}

运行结果如下:

pool-1-thread-2 is running

pool-1-thread-3 is running

Exception in thread "main" java.util.concurrent.RejectedExecutionException

pool-1-thread-1 is running

pool-1-thread-7 is running

pool-1-thread-6 is running

pool-1-thread-4 is running

pool-1-thread-9 is running

pool-1-thread-8 is running

pool-1-thread-5 is running

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1760)

at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:767)

at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:658)

at concurrent.ThreadPoolDemo.main(ThreadPoolDemo.java:33)

pool-1-thread-10 is running

处理源码如下:

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {

throw new RejectedExecutionException();

}

策略2:ThreadPoolExecutor.CallerRunsPolicy
用于被拒绝任务的处理程序,它直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务。如下:

RejectedExecutionHandler handler =

new ThreadPoolExecutor.CallerRunsPolicy();

运行如下:

pool-1-thread-7 is running

pool-1-thread-7 is running

pool-1-thread-7 is running

pool-1-thread-7 is running

pool-1-thread-7 is running

pool-1-thread-7 is running

pool-1-thread-2 is running

pool-1-thread-3 is running

pool-1-thread-1 is running

pool-1-thread-8 is running

main is running

main is running

main is running

pool-1-thread-4 is running

pool-1-thread-7 is running

pool-1-thread-7 is running

pool-1-thread-7 is running

处理源码如下:

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {

if (!e.isShutdown()) {

r.run();

}

}

策略3:

RejectedExecutionHandler handler =

new ThreadPoolExecutor.DiscardOldestPolicy();

这样运行结果就不会有100个线程全部被执行。处理源码如下:

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {

if (!e.isShutdown()) {

e.getQueue().poll();

e.execute(r);

}

}

策略4:ThreadPoolExecutor.DiscardPolicy
用于被拒绝任务的处理程序,默认情况下它将丢弃被拒绝的任务。

运行结果也不会全部执行100个线程。

源码如下,实际就是对线程不执行操作:

public static class DiscardPolicy implements RejectedExecutionHandler {

/**

* Creates a <tt>DiscardPolicy</tt>.

*/

public DiscardPolicy() { }

/**

* Does nothing, which has the effect of discarding task r.

* @param r the runnable task requested to be executed

* @param e the executor attempting to execute this task

*/

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {

}

}

这四种策略是独立无关的,是对任务拒绝处理的四中表现形式。最简单的方式就是直接丢弃任务。但是却有两种方式,到底是该丢弃哪一个任务,比如可以丢弃当前将要加入队列的任务本身(DiscardPolicy)或者丢弃任务队列中最旧任务(DiscardOldestPolicy)。丢弃最旧任务也不是简单的丢弃最旧的任务,而是有一些额外的处理。除了丢弃任务还可以直接抛出一个异常(RejectedExecutionException),这是比较简单的方式。抛出异常的方式(AbortPolicy)尽管实现方式比较简单,但是由于抛出一个RuntimeException,因此会中断调用者的处理过程。除了抛出异常以外还可以不进入线程池执行,在这种方式(CallerRunsPolicy)中任务将有调用者线程去执行。

原文地址: https://blog.csdn.net/pozmckaoddb/article/details/51478017

线程池ThreadPoolExecutor里面4种拒绝策略的更多相关文章

  1. 转载-ThreadPoolExecutor里面4种拒绝策略(详细)

    原文链接:https://blog.csdn.net/wjs19930820/article/details/79849050 1 /** * 定义异步任务执行线程池 */ @Configuratio ...

  2. ThreadPoolExecutor里面4种拒绝策略(详细)

    ThreadPoolExecutor类实现了ExecutorService接口和Executor接口,可以设置线程池corePoolSize,最大线程池大小,AliveTime,拒绝策略等.常用构造方 ...

  3. JUC之线程池的实现原理以及拒绝策略

    线程池实现原理 向线程池提交任务后,线程池如何来处理这个任务,之前我们了解了7个参数,我们通过这些参数来串联其线程池的实现原理. 1.在创建了线程池后,开始等待请求 2.当调用execute()方法添 ...

  4. 线程池ThreadPoolExecutor的一种扩展办法

    概述 在JAVA的世界里,如果想并行的执行一些任务,可以使用ThreadPoolExecutor. 大部分情况下直接使用ThreadPoolExecutor就可以满足要求了,但是在某些场景下,比如瞬时 ...

  5. 浅析线程池 ThreadPoolExecutor 源码

    首先看下类的继承关系,不多介绍: public interface Executor {void execute(Runnable);} public interface ExecutorServic ...

  6. Java-五种线程池,四种拒绝策略,三种阻塞队列(转)

    Java-五种线程池,四种拒绝策略,三种阻塞队列 三种阻塞队列:    BlockingQueue<Runnable> workQueue = null;    workQueue = n ...

  7. JUC之线程池-三大方法-七大参数-四种拒绝策略

    线程池:重点 三大方法 七大参数 四种拒绝策略 使用池化技术的理由: 我们的程序伴随着创建销毁线程十分浪费资源, 所以使用线程池,先创建线程,随用随取,用完归还 简单来说就是节约了资源. 使用线程池的 ...

  8. Java 线程池四种拒绝策略

    jdk1.5版本新增了 JUC 并发包,其中一个包含线程池. 四种拒绝策略: 拒绝策略类型 说明 1 ThreadPoolExecutor.AbortPolicy 默认拒绝策略,拒绝任务并抛出任务 2 ...

  9. ThreadPoolExecutor八种拒绝策略浅析

    转自:http://www.kailing.pub/article/index/arcid/255.html 前言 谈到java的线程池最熟悉的莫过于ExecutorService接口了,jdk1.5 ...

随机推荐

  1. 【BZOJ4554】[Tjoi2016&Heoi2016]游戏 二分图最大匹配

    [BZOJ4554][Tjoi2016&Heoi2016]游戏 Description 在2016年,佳缘姐姐喜欢上了一款游戏,叫做泡泡堂.简单的说,这个游戏就是在一张地图上放上若干个炸弹,看 ...

  2. ios开发 点击文本(TextField)输入的时候向上推以及输入之后恢复的动画

    1.添加委托UITextFieldDelegate 2. -(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resi ...

  3. ehcache加载配置文件ehcache.xml的源码

    package net.sf.ehcache.config; public final class ConfigurationFactory { public static Configuration ...

  4. postgresql----字符串函数与操作符

    函数 返回值类型 描述 示例 结果 string||string text 字符串连接 select 'Post'||'gresql'||' good!'; Postgresql good! stri ...

  5. postgresql----时间类型

    postgresql支持的时间类型如下图所示: 日期 date: 建议日期的输入格式为1997-01-01,虽然也支持19970101,1/1/1997,Jan-1-1997等多种格式. 时间戳 ti ...

  6. 限制ip ssh远程登录

    有时候为了服务器的安全考虑,我们可以在服务器上做限制,禁止其他ip地址连接服务器. 方法一:修改ssh配置文件 其实做这个操作很简单,只需要改/etc/ssh/sshd_config配置文件,再最后一 ...

  7. java网络编程面试题

    1.网络编程时的同步.异步.阻塞.非阻塞? 同步:函数调用在没得到结果之前,没有调用结果,不返回任何结果.异步:函数调用在没得到结果之前,没有调用结果,返回状态信息.阻塞:函数调用在没得到结果之前,当 ...

  8. 更快写入的落脚点不是线程数而是mysql连接数 对数据库 批处理 批写入

    批提交mysql 单线程的批提交 nohup  python fromRedisoToMysqlSingleThreadOneConnBatchInsert.py 100 10.24.192.192 ...

  9. Constructor Overloading in Java with examples 构造方法重载 Default constructor 默认构造器 缺省构造器 创建对象 类实例化

    Providing Constructors for Your Classes (The Java™ Tutorials > Learning the Java Language > Cl ...

  10. 7.如何将python脚本打包为exe形式

    先安装pyinstaller,pip install pyinstaller 然后 pyinstaller -F combine.py打包即可