自定义线程池核心参数
Posted 迷思t无
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义线程池核心参数相关的知识,希望对你有一定的参考价值。
核心参数
核心线程数 corePoolSize
如果没有设置允许主线程过期,核心线程数为线程池中保留的最大线程数
最大线程数 maximumPoolSize
线程池能创建的最大工作线程数
线程存活时间 keepAliveTime,时间类型unit
即超过核心线程数的线程过期的时间,在指定时间内未获取到任务的话,则会回收线程。
任务队列 BlockingQueue
存放任务的阻塞队列,符合先进先出原则。有ArrayListBlockingQueue和LinkedBlockQueue两种。
线程工厂 ThreadFactory
创建一个线程工厂,线程池中的线程都由该工厂创建,有统一的线程前缀,可根据不同业务定义,方便定位问题。
拒绝策略 RejectedExecutionHandler
线程超过最大线程数时,线程池对新任务的处理策略,共四种
AbortPolicy(默认)
不接受任务,直接抛出异常
CallerRunsPolicy
由提交任务的线程执行该任务,通常是请求线程执行。不允许任务丢失的业务可以使用该策略
DiscardPolicy
不接受任务,抛弃掉该任务
DiscardOldestPolicy
接受该任务,放弃队列中最早的任务
构造方法 共四个(三个重载方法)
//不指定线程工厂和拒绝策略(默认Abort)
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
//不指定拒绝策略(默认Abort)
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
//不指定线程工厂
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
//所有参数
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;
}
使用示例
// 打印线程名
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(8, 16, 200,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(200), new MyThreadFactory("test-thread-pool-"), new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 10; i++) {
threadPoolExecutor.execute(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i am " + Thread.currentThread().getName());
});
}
输出:
以上是关于自定义线程池核心参数的主要内容,如果未能解决你的问题,请参考以下文章
newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段
Java 并发编程线程池机制 ( 线程池阻塞队列 | 线程池拒绝策略 | 使用 ThreadPoolExecutor 自定义线程池参数 )