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

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并发编程--ThreadPoolExecutor

    概述 为什么要使用线程池? 合理利用线程池能够带来三个好处.第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗.第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立 ...

  7. Java线程池的拒绝策略

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

  8. JAVA并发(8)-ThreadPoolExecutor的讲解

    很久前(2020-10-23),就有想法学习线程池并输出博客,但是写着写着感觉看不懂了,就不了了之了.现在重拾起,重新写一下(学习一下). 线程池的优点也是老生常谈的东西了 减少线程创建的开销(任务数 ...

  9. java并发:初探sleep方法

    sleep与wait sleep是Thread方法,使得当前线程从运行态变为阻塞态.但它不会释放对象的锁. wait方法是Object方法,它的作用是使得当前拥有对象锁的线程从运行态变为阻塞态, 它会 ...

随机推荐

  1. 带有“全选”的combotree

    <div id="setBtn_dd" class="easyui-window" data-options="iconCls:'icon-sa ...

  2. POJ1087 A Plug of UNIX

    你作为某高管去住宿了,然后宾馆里有几种插座,分别有其对应型号,你携带了几种用电器(手机,电脑一类的),也有其对应型号:可是不一定用电器就能和插座匹配上,于是宾馆的商店里提供了一些转换器,这些转换器可以 ...

  3. Django rest framework框架中有哪些组件

    认证 权限(授权) 用户访问次数/频率限制 版本 解析器(parser) 序列化 分页 路由系统 视图 渲染器 认证 自定义认证的类 """ from rest_fram ...

  4. CN109241772A发票区块链记录方法、装置、区块链网关服务器和介质(腾讯)

    学习笔记-2 CN109241772A发票区块链记录方法.装置.区块链网关服务器和介质(腾讯) 解决什么问题? 让发票信息记录到区块链的情况下减少发票信息泄露 链上有什么数据? 发行发票事件信息(发票 ...

  5. win10使用L2TP连接失败,报远程服务器未响应错误解决办法,亲测可用!

    报错如下: 原因是L2TP连接需要IPSec加密,远程服务器未响应说明IPSec加密被禁用了,需要在注册表启用它,具体步骤如下: 1.以管理员账号身份打开CMD,win10 是 win+x键 2.找到 ...

  6. MAC系统 - 系统目录结构

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/smstong/article/detai ...

  7. mybatis 无效字符

    只想说 是真的坑啊!!!!!sql就是对 但就是报错无效字符..... 一.sql后有 “:”,我觉得这个应该坑了很多人了 二.标签后有类似于空格的东西(我也不知道是tab还是空格,反正删完就对了) ...

  8. Python 之并发编程之线程下

    七.线程局部变量 多线程之间使用threading.local 对象用来存储数据,而其他线程不可见 实现多线程之间的数据隔离 本质上就是不同的线程使用这个对象时,为其创建一个只属于当前线程的字典 拿空 ...

  9. ios中使用socket实现聊天

    [iOS]SocketRocket简单实现聊天室功能 https://www.jianshu.com/p/db34940f1135      CocoaAsyncSocket   https://gi ...

  10. Do You Know These Plastic Bottle Processing Terms?

    The molding process of a plastic bottle refers to a process of making a final plastic article from a ...