Java线程池 ThreadPoolExecutor类
什么是线程池?
- java线程池是将大量的线程集中管理的类, 包括对线程的创建, 资源的管理, 线程生命周期的管理。
- 当系统中存在大量的异步任务的时候就考虑使用java线程池管理所有的线程, 从而减少系统资源的开销。
阿里的开发手册规范
- 线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样 的处理方式让写的人更加明确线程池的运行规则,规避资源耗尽的风险。
- Executors 返回的线程池对象的弊端如下:
- FixedThreadPool 和 SingleThreadPool: 允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
- CachedThreadPool 和 ScheduledThreadPool: 允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。
线程池的创建
- new ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue workQueue,RejectedExecutionHandler handler)
- corePoolSize: 线程池维护线程的最少数量
- maximumPoolSize: 线程池维护线程所允许的空闲时间
- unit: 线程池维护线程锁允许的空闲时间的单位
- workQueue: 线程池锁使用的缓冲队列
- handler: 线程池对拒绝任务的处理策略
添加任务到线程池
-
通过execute(Runnable) 方法添加到线程池, 任务就是一个Runnable类型的对象, 任务的执行方法就是Runnable类型对象的run()方法。
-
当一个任务通过execute(Runnable) 方法欲添加到线程池时:
- 如果此时线程池中线程的数量小于corePoolSize, 即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
- 如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列
- 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。
- 如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。
-
也就是说:
- 处理任务的优先级为:
- 核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。
- 处理任务的优先级为:
-
当线程池中的线程数量大于 corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止。这样,线程池可以动态的调整池中的线程数。
-
unit可选的参数为java.util.concurrent.TimeUnit中的几个静态属性:NANOSECONDS、MICROSECONDS、MILLISECONDS、SECONDS。
-
workQueue常用的是:java.util.concurrent.ArrayBlockingQueue
-
handler的四个选择:
-
ThreadPoolExecutor.AbortPolicy() [直译过来流产计划?]
-
抛出 java.util.concurrent.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()); } }
-
-
ThreadPoolExecutor.CallerRunsPolicy()
-
重试添加当前的任务,它会自动重复调用execute()方法
/** * 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. * 在调用者的线程中执行任务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) { if (!e.isShutdown()) { r.run(); } } }
-
-
ThreadPoolExecutor.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. * 获取并忽视下一个执行器会执行的任务, 如果其中一个是当前可获取的, 并且 *多次重试执行过任务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) { if (!e.isShutdown()) { e.getQueue().poll(); e.execute(r); } } } }
-
-
ThreadPoolExecutor.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. * 什么都不做, 就有抛弃任务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) { } }
-
-
测试线程池Demo
package com.ronnie;
import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {
private static int produceTaskSleepTime = 5;
private static int consumeTaskSleepTime = 5000;
private static int produceTaskMaxNumber = 20; // 定义最大添加20个线程到线程池中
/**
* 线程池执行的任务
*/
public static class ThreadPoolTask implements Runnable, Serializable{
private static final long serialVersionUID = 0;
// 保存任务所需要的数据
private Object threadPoolTaskData;
ThreadPoolTask(Object works){
this.threadPoolTaskData = works;
}
@Override
public void run() {
// 处理一个任务
System.out.println(threadPoolTaskData + "started......");
try {
// 便于观察, 等待一段时间
Thread.sleep(consumeTaskSleepTime);
} catch (Exception e){
e.printStackTrace();
}
threadPoolTaskData = null;
}
public Object getTask(){
return this.threadPoolTaskData;
}
}
public static void main(String[] args) {
// 构造一个线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(6, 12, 9,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(6), new ThreadPoolExecutor.DiscardOldestPolicy());
for (int i = 1; i <= produceTaskMaxNumber; i++){
try {
// 创建一个任务并将其加入线程池
String work = "work@: " + i;
System.out.println("put: " + work);
threadPool.execute(new ThreadPoolTask(work));
// 等待一会儿, 便于观察
Thread.sleep(produceTaskSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
-
执行结果
put: work@: 1 work@: 1started...... put: work@: 2 work@: 2started...... put: work@: 3 work@: 3started...... put: work@: 4 work@: 4started...... put: work@: 5 work@: 5started...... put: work@: 6 work@: 6started...... put: work@: 7 put: work@: 8 put: work@: 9 put: work@: 10 put: work@: 11 put: work@: 12 put: work@: 13 work@: 13started...... put: work@: 14 work@: 14started...... put: work@: 15 work@: 15started...... put: work@: 16 work@: 16started...... put: work@: 17 work@: 17started...... put: work@: 18 work@: 18started...... put: work@: 19 put: work@: 20 work@: 9started...... work@: 10started...... work@: 11started...... work@: 12started...... work@: 19started...... work@: 20started......