学而不思则罔,思而不学则殆
【线程池】线程池(一)- 七个参数详解
总结
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
...
}
参数 | 解释 | 说明 |
---|---|---|
corePoolSize | 线程池核心线程大小 | |
maximumPoolSize | 池中允许的最大线程数 | |
keepAliveTime | ||
unit | ||
workQueue | ||
threadFactory | ||
handler |
参数详解
corePoolSize
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
线程池中会维护一个最小的线程数量,即使这些线程处理空闲状态,他们也不会被销毁,除非设置了allowCoreThreadTimeOut。这里的最小线程数量即是corePoolSize。
定义一个corePoolSize =1的一个线程池:
运行两个线程:
executor.execute(() -> {
System.out.println(Thread.currentThread().getName());
});
executor.execute(() -> {
System.out.println(Thread.currentThread().getName());
});
查看核心线程个数:
println("corePoolSize:" + executor.getCorePoolSize());
展示的结果:
pool-1-thread-1
pool-1-thread-2
corePoolSize:1
poolSize:1
activeCount:0
而且两个线程运行结束以后核心线程一直在运行,程序也没有停止。
通过jstack查看线程运行状态:
发现【pool-1-thread-2】这个线程被park,处于WAITING状态,此时等待新的任务加进来复用这个线程。
当我们设置:
时候:
线程池的两个任务运行结束后,10s没有添加新任务,线程池的线程都停止了,包括核心线程:
这里虽然核心线程的个数等于1,实际是没有运行中的线程的。通过jstack命令查看,也找不到线程池相关的线程处于非死亡状态的。
maximumPoolSize - 池中允许的最大线程数
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
一个任务被提交到线程池后,首先会缓存到工作队列(后面会介绍)中,如果工作队列满了,则会创建一个新线程,然后从工作队列中的取出一个任务交由新线程来处理,而将刚提交的任务放入工作队列。线程池不会无限制的去创建新线程,它会有一个最大线程数量的限制,这个数量即由maximunPoolSize来指定。
keepAliveTime 空闲线程存活时间
* @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.
当线程数量大于核心时,这是多余空闲线程在终止前等待新任务的最大时间。
一个线程如果处于空闲状态,并且当前的线程数量大于corePoolSize,那么在指定时间后,这个空闲线程会被销毁,这里的指定时间由keepAliveTime来设定(如果没新的任务来使用它的话)
unit 空闲线程存活时间单位
空间线程存活时间单位:
NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS
workQueue 工作队列
新任务被提交后,会先进入到此工作队列中,任务调度时再从队列中取出任务。
原生提供了四种工作队列:
工作队列总结
队列 | 说明 | 补充 |
---|---|---|
LinkedBlockingQuene | 任务个数无上限,maximumPoolSize 无效 | |
ArrayBlockingQueue | 任务数量达到corePoolSize放到队列尾,数量达到maximumPoolSize 执行拒绝策略 | 会抛出异常,注意捕获 |
SynchronousQuene | 有可用线程,直接加入,没有可以用线程执行拒绝策略 | 会抛出异常,注意捕获 |
PriorityBlockingQueue | 任务个数无上限, maximumPoolSize 无效 |
LinkedBlockingQuene
基于链表的无界阻塞队列(其实最大容量为Interger.MAX),按照FIFO排序。由于该队列的近似无界性,当线程池中线程数量达到corePoolSize后,再有新任务进来,会一直存入该队列,而不会去创建新线程直到maxPoolSize,因此使用该工作队列时,参数maxPoolSize其实是不起作用的。
Java原生代码中单线程池采用了这个工作队列,
小测试:
先系统单线程池的基础上把maximumPoolSize 线程数改为2,往线程池中加入三个任务:
static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(), createFactory("zy", false));
测试结果如下:
1600387430806 : corePoolSize:1
1600387430806 : poolSize:1
1600387430806 : activeCount:1
1600387430806 : MaximumPoolSize:2
1600387430806 : Queue().size:2
当前只有一个线程在运行即核心线程池,MaximumPoolSize没有生效,队列中有两个任务处于等待执行的状态。
ArrayBlockingQueue
基于数组的有界阻塞队列,按FIFO排序。新任务进来后,会放到该队列的队尾,有界的数组可以防止资源耗尽问题。当线程池中线程数量达到corePoolSize后,再有新任务进来,则会将任务放入该队列的队尾,等待被调度。如果队列已经是满的,则创建一个新线程,如果线程数量已经达到maxPoolSize,则会执行拒绝策略。
测试:
添加一个ArrayBlockingQueue个数为1的工作队列。
static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(1), createFactory("zy-pool", false));
加入三个任务:
结果如下:
zy-pool-0
zy-pool-1
zy-pool-0
zy-pool-1
1600388335424 : corePoolSize:1
1600388335424 : poolSize:2
1600388335424 : activeCount:2
1600388335424 : MaximumPoolSize:2
1600388335424 : Queue().size:1
共有两个任务线程在执行,队列中有一个任务在等待。
加入四个任务:
结果如下:
zy-pool-0
zy-pool-1
1600388450495 : corePoolSize:1
1600388450495 : poolSize:2
1600388450495 : activeCount:2
1600388450495 : MaximumPoolSize:2
1600388450496 : Queue().size:1
1600388450496 : ---
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.thread.ThreadPoolDemo$$Lambda$6/1531448569@6f496d9f rejected from java.util.concurrent.ThreadPoolExecutor@723279cf[Running, pool size = 2, active threads = 2, queued tasks = 1, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at com.thread.ThreadPoolDemo.main(ThreadPoolDemo.java:96)
抛出了异常,采用的AbortPolicy 拒绝策略。但是呢之前加入的任务还是在正常执行。
SynchronousQuene
一个不缓存任务的阻塞队列,生产者放入一个任务必须等到消费者取出这个任务。也就是说新任务进来时,不会缓存,而是直接被调度执行该任务,如果没有可用线程,则创建新线程,如果线程数量达到maxPoolSize,则执行拒绝策略。
小测试:
static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
0L, TimeUnit.MILLISECONDS,
new SynchronousQueue<Runnable>(), createFactory("zy-pool", false));
添加四个任务,结果如下:
java.util.concurrent.RejectedExecutionException: Task com.thread.ThreadPoolDemo$$Lambda$3/2065951873@3feba861 rejected from java.util.concurrent.ThreadPoolExecutor@5b480cf9[Running, pool size = 2, active threads = 2, queued tasks = 0, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at com.thread.ThreadPoolDemo.addTask(ThreadPoolDemo.java:53)
at com.thread.ThreadPoolDemo.main(ThreadPoolDemo.java:45)
java.util.concurrent.RejectedExecutionException: Task com.thread.ThreadPoolDemo$$Lambda$3/2065951873@3feba861 rejected from java.util.concurrent.ThreadPoolExecutor@5b480cf9[Running, pool size = 2, active threads = 2, queued tasks = 0, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at com.thread.ThreadPoolDemo.addTask(ThreadPoolDemo.java:53)
at com.thread.ThreadPoolDemo.main(ThreadPoolDemo.java:46)
zy-pool-0
zy-pool-1
zy-pool-0
zy-pool-1
1600388791331 : corePoolSize:1
1600388791331 : poolSize:2
1600388791331 : activeCount:2
1600388791331 : MaximumPoolSize:2
1600388791331 : Queue().size:0
运行中的任务有两个,等于MaximumPoolSize=2,队列中没有任务,个数为0.
PriorityBlockingQueue
具有优先级的无界阻塞队列,优先级通过参数Comparator实现。
小测试:
static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
0L, TimeUnit.MILLISECONDS,
new PriorityBlockingQueue<Runnable>(1, new Comparator<Runnable>() {
@Override
public int compare(Runnable o1, Runnable o2) {
return 0;
}
}), createFactory("zy-pool", false));
添加4个任务:
zy-pool-0
zy-pool-0
zy-pool-0
1600389180074 : corePoolSize:1
1600389180074 : poolSize:1
1600389180074 : activeCount:1
1600389180074 : MaximumPoolSize:2
1600389180074 : Queue().size:3
1600389180074 : ---
zy-pool-0
zy-pool-0
有一个任务,corePoolSize=1 在执行,MaximumPoolSize不生效,队列中有3个任务在等待
threadFactory 线程工厂
创建一个新线程时使用的工厂,可以用来设定线程名、是否为daemon线程等等
可以采用默认的,也是自定义实现:
自定义实现:
private static ThreadFactory createFactory(final String name, boolean daemon) {
AtomicInteger atomicInteger = new AtomicInteger();
return (r) -> {
Thread thread = new Thread(r, name + "-" + atomicInteger.getAndIncrement());
thread.setDaemon(daemon);
return thread;
};
}
提供的默认工厂:
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 static ThreadFactory defaultThreadFactory() {
return new DefaultThreadFactory();
}
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
不设置自己的线程工厂的时候,一般是采取默认的工厂。
handler 拒绝策略
当工作队列中的任务已到达最大限制,并且线程池中的线程数量也达到最大限制,这时如果有新任务提交进来,该如何处理呢。这里就拒绝策略干的事;
拒绝策略的是一个接口,默认有四种实现对应四种策略:
public interface RejectedExecutionHandler {
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
默认拒绝策略总结
子类 | 策略 | 异常 |
---|---|---|
AbortPolicy | 直接抛弃 | 抛出异常 |
CallerRunsPolicy | 如果线程池没有shutdown,在调用者线程中直接执行被拒绝任务的run方法,否则抛弃任务 | 不抛出异常 |
DiscardOldestPolicy | 抛弃进入队列最早的那个任务,然后尝试把这次拒绝的任务放入队列 | 不抛出异常 |
DiscardPolicy | 直接丢弃任务,什么都不做 | 不抛出异常 |
AbortPolicy
该策略下,直接丢弃任务,并抛出RejectedExecutionException异常。
/**
* 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 r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
CallerRunsPolicy
该策略下,在调用者线程中直接执行被拒绝任务的run方法,除非线程池已经shutdown,则直接抛弃任务,不抛出异常。
/**
* 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();
}
}
}
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);
}
}
}
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) {
}
}