ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
...
}
mExecutor = new ThreadPoolExecutor(corePoolSize,// 核心线程数
maximumPoolSize, // 最大线程数
keepAliveTime, // 闲置线程存活时间
TimeUnit.MILLISECONDS,// 时间单位
new LinkedBlockingDeque<Runnable>(),// 线程队列
Executors.defaultThreadFactory(),// 线程工厂
new AbortPolicy()// 队列已满,而且当前线程数已经超过最大线程数时的异常处理策略
);
corePoolSize: 该线程池中核心线程的数量
maximumPoolSize:该线程池中最大线程数量。(区别于corePoolSize)
keepAliveTime:从字面上就可以理解,是非核心线程空闲时要等待下一个任务到来的时间,当任务很多,每个任务执行时间很短的情况下调大该值有助于提高线程利用率。注意:当allowCoreThreadTimeOut属性设为true时,该属性也可用于核心线程。
unit:上面时间属性的单位
workQueue:任务队列
ArrayBlockingQueue :一个由数组结构组成的有界阻塞队列。
LinkedBlockingQueue:一个由链表结构组成的有界阻塞队列。
PriorityBlockingQueue :一个支持优先级排序的无界阻塞队列。
DelayQueue:一个使用优先级队列实现的无界阻塞队列。
SynchronousQueue:一个不存储元素的阻塞队列。
LinkedTransferQueue:一个由链表结构组成的无界阻塞队列。
LinkedBlockingDeque:一个由链表结构组成的双向阻塞队列。
adFactory:线程工厂,可用于设置线程名字等等,一般无须设置该参数。
//创建基本线程池
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3,5,1,TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(100));
//创建fixed线程池,参数为核心线程数,只有核心线程,无非核心线程,并且阻塞队列无界。采用LinkedBlockingQueue
final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
//创建Cached线程池,没有核心线程,只有非核心线程,并且每个非核心线程空闲等待的时间为60s,采用SynchronousQueue队列。
final ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
//创建Single线程池,只有一个核心线程,当被占用时,其他的任务需要进入队列等待,采用LinkedBlockingQueue
final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
//创建Scheduled线程池,延迟启动任务,使用方法scheduledThreadPool.(runnable,10,TimeUnit.SECONDS);
final ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);