ThreadPoolExecutor自定义线程池
1.ThreadPoolExecutor创建线程池的构造函数
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
参数简介:
- corePoolSize:核心线程数量
- maximumPoolSize:最大线程数量
- keepAliveTime:没有执行任务的线程,最大空闲时间
- unit:时间单位,TimeUnit.DAYS,TimeUnit.HOURS,TimeUnit.MINUTES,TimeUnit.SECONDS,TimeUnit.MILLISECONDS
TimeUnit.MICROSECONDS,TimeUnit.NANOSECONDS,七种
- BlockingQueue<Runnable> workQueue:一个阻塞队列,用来存储等待执行的任务,
ArrayBlockingQueue,LinkedBlockingQueue,SynchronousQueue三种
- ThreadFactory threadFactory:创建线程的工厂类
- RejectedExecutionHandler handler:拒绝策略
2.拒绝策略 拒绝策略: 四种拒绝策略,实现:RejectedExecutionHandler接口 1.AbortPolicy(中止策略,抛出异常,默认的策略)
源码: /** * A handler for rejected tasks that throws a * {@code RejectedExecutionException}. / public static class AbortPolicy implements RejectedExecutionHandler { /* * Creates an {@code AbortPolicy}. */ public AbortPolicy() { }
/**
* Always throws RejectedExecutionException.
*
* [@param](https://my.oschina.net/u/2303379) r the runnable task requested to be executed
* [@param](https://my.oschina.net/u/2303379) e the executor attempting to execute this task
* [@throws](https://my.oschina.net/throws) RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
2.CallerRunsPolicy(由调用线程处理该任务)
源码: /** * 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 { /* * Creates a {@code CallerRunsPolicy}. */ public CallerRunsPolicy() { }
/**
* Executes task r in the caller's thread, unless the executor
* has been shut down, in which case the task is discarded.
*
* @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) {
if (!e.isShutdown()) {
r.run();
}
}
}
3.DiscardOldestPolicy(丢弃队列最前面的任务,然后重新提交被拒绝的任务)
源码: /** * 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 { /* * Creates a {@code DiscardOldestPolicy} for the given executor. */ public DiscardOldestPolicy() { }
/**
* Obtains and ignores the next task that the executor
* would otherwise execute, if one is immediately available,
* and then retries execution of task r, unless the executor
* is shut down, in which case task r is instead discarded.
*
* @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) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}
4.DiscardPolicy(丢弃任务,但是不抛出异常。如果线程队列已满,则后续提交的任务都会被丢弃,且是静默丢弃)
源码: /** * A handler for rejected tasks that silently discards the * rejected task. / public static class DiscardPolicy implements RejectedExecutionHandler { /* * Creates a {@code DiscardPolicy}. */ 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) {
}
}
根据实际需求,制定合适的拒绝策略
来源:江苏网站优化
ThreadPoolExecutor自定义线程池的更多相关文章
- Android线程管理之ThreadPoolExecutor自定义线程池
前言: 上篇主要介绍了使用线程池的好处以及ExecutorService接口,然后学习了通过Executors工厂类生成满足不同需求的简单线程池,但是有时候我们需要相对复杂的线程池的时候就需要我们自己 ...
- 基于ThreadPoolExecutor,自定义线程池简单实现
一.线程池作用 在上一篇随笔中有提到多线程具有同一时刻处理多个任务的特点,即并行工作,因此多线程的用途非常广泛,特别在性能优化上显得尤为重要.然而,多线程处理消耗的时间包括创建线程时间T1.工作时间T ...
- 自定义线程池的名称(ThreadPoolExecutor)
目的:有时候为了快速定位出现错误的位置,在采用线程池时我们需要自定义线程池的名称. 1.创建ThreadFactory(ThreadPoolExecutor默认采用的是DefaultThreadFac ...
- 自定义线程池ThreadPoolExecutor
使用自定义的方式创建线程池 Java本身提供的获取线程池的方式 使用Executors直接获取线程池,注意,前四个方式的底层都是通过new ThreadPoolExecutor()的方式创建的线程池, ...
- Android AsyncTask 深度理解、简单封装、任务队列分析、自定义线程池
前言:由于最近在做SDK的功能,需要设计线程池.看了很多资料不知道从何开始着手,突然发现了AsyncTask有对线程池的封装,so,就拿它开刀,本文将从AsyncTask的基本用法,到简单的封装,再到 ...
- JAVA并发,线程工厂及自定义线程池
package com.xt.thinks21_2; import java.util.concurrent.ExecutorService; import java.util.concurrent. ...
- java多线程(四)-自定义线程池
当我们使用 线程池的时候,可以使用 newCachedThreadPool()或者 newFixedThreadPool(int)等方法,其实我们深入到这些方法里面,就可以看到它们的是实现方式是这样的 ...
- SOFA 源码分析 — 自定义线程池原理
前言 在 SOFA-RPC 的官方介绍里,介绍了自定义线程池,可以为指定服务设置一个独立的业务线程池,和 SOFARPC 自身的业务线程池是隔离的.多个服务可以共用一个独立的线程池. API使用方式如 ...
- Java自定义线程池-记录每个线程执行耗时
ThreadPoolExecutor是可扩展的,其提供了几个可在子类化中改写的方法,如下: protected void beforeExecute(Thread t, Runnable r) { } ...
随机推荐
- Python Learning Day9
Scrapy爬虫框架 发送请求 ---> 获取响应数据 ---> 解析数据 ---> 保存数据 Scarpy框架介绍 1.引擎(EGINE) 引擎负责控制系统所有组件之间的数据流,并 ...
- 欧拉回路--P2731 骑马修栅栏 Riding the Fences
实在懒得复制题干了 *传送 1.定义 *如果图G(有向图或者无向图)中所有边一次仅且一次行遍所有顶点的通路称作欧拉通路. *如果图G中所有边一次仅且一次行遍所有顶点的回路称作欧拉回路. *具有欧拉回路 ...
- Swift—UITextField的基本用法
https://www.jianshu.com/p/63bdeca39ddf 1.文本输入框的创建##### let textField = UITextField(frame: CGRect(x:1 ...
- centos 7.4 磁盘空间不足,扩容根分区 --lvm模式
背景:根分区磁盘空间不足,需要扩容root磁盘空间 1.查看现有磁盘信息,可以看出根分区有26G [root@localhost ~]# df -h 2.查看新增加的磁盘信息(改虚拟机已经添加好了,不 ...
- PTA 天梯赛 L1
L1-002 打印沙漏 细节:就是在 (i>j&&i+j<r+1) 这个区间里才有空格,然后就是 for 循环 for(r=1; ;r+=2) 条件不满足之后还会再 ...
- python类(4)——自己造第一个轮子
先做简单版本,再一步步增加功能 1.简单目的:要实现这样一个功能,能够连接服务器,登录账号,查询账号委托信息,如果有委托信息,撤销委托. 属性(不同账户之间差别):账户,密码 方法(不同账户之间都要用 ...
- C语言的字符串类型
C语言使用指针来管理字符串(1)C语言中定义字符串的方法:char *p = "linux";此时p就叫字符串,但是实际上p只是一个字符指针(本质上就是一个指针变量,只是p指向了一 ...
- Java编程知识点梳理
1. elementAt() temp.elementAt(0) 返回temp这个vector里面存放的第一个元素--->也是一个vector类型. 2. 字符串空格分割 String [] ...
- python + selenium +win32gui + winspy 实现图片上传
过程:模拟点击上传按钮,打开Windows对话框,编辑栏输入文件路径(或网址)点击确定.网上随便找了一个进行测试. 点击后出现Windows上传对话框 用 winspy 来检测窗口的句柄 python ...
- kaggle——贷款信用评估介绍
介绍 对于金融机构的贷款业务来说,一个顾客的信用信息是极其重要的.因为只有了解客户的信用情况,才能决定是否通过客户的贷款申请.本次将会介绍如何根据用户的一些基本信息来判断顾客的信用或贷款偿还能力. 知 ...