1.线程池入参
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
1.corePoolSize
核心线程数量,线程池维护的最小线程数量,没任务也不会销毁线程
2.maximumPoolSize
最大线程数量,一个任务被提交到线程池以后,首先会找有没有空闲存活线程,如果有则直接执行,如果没有则会缓存到阻塞队列中,如果队列满了,才会创建一个新线程,然后从队列的头部取出一个任务交由新线程来处理,而将刚提交的任务放入队列尾部。线程池不会无限制的去创建新线程,它会有一个最大线程数量的限制,这个数量即由maximunPoolSize指定。
3.keepAliveTime
当线程数量大于核心线程数时,空闲线程存活的时间(一直没有新任务到来)
4.unit
keepAliveTime的时间单位
5.workQueue 工作队列
1.LinkedBlockingQueue 链表阻塞队列
由链表支持的无界阻塞队列
//默认容量大小
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
2.SynchronousQueue 同步队列
//默认是非公平策略
public SynchronousQueue() {
this(false);
}
//公平策略由队列实现,先进先出;非公平策略由栈实现,先进后出
public SynchronousQueue(boolean fair) {
transferer = fair ? new TransferQueue<E>() : new TransferStack<E>();
}
3.DelayedWorkQueue 延迟队列
4.ArrayBlockingQueue 数组阻塞队列
由数组支持的有界(需要提前设置大小,不能更改)阻塞队列;
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
5.PriorityBlockingQueue 无阻塞排序队列
public PriorityBlockingQueue(int initialCapacity,
Comparator<? super E> comparator) {
if (initialCapacity < 1)
throw new IllegalArgumentException();
this.lock = new ReentrantLock();
this.notEmpty = lock.newCondition();
this.comparator = comparator;
this.queue = new Object[initialCapacity];
}
6.threadFactory 线程工厂
所有的线程都是通过threadFactory来创建,可以初始化优先级、名称、是否守护线程等
通过addWorker方法创建线程
private boolean addWorker(Runnable firstTask, boolean core) {
...
Worker w = null;
try {
w = new Worker(firstTask);
...
}
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
jdk默认threadFactory
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) //线程优先级,默认是5,范围(1-10)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
7.handler 拒绝策略
当达到线程数量上限和任务队列上限的时候,仍有新任务提交,就会执行拒绝策略。
CallerRunsPolicy:直接运行策略 此策略如果线程池没有中止,直接运行此任务
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
AbortPolicy:终止策略 此策略丢弃任务,并抛出异常(jdk默认拒绝策略)
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
DiscardPolicy:丢弃策略 此策略丢弃任务,不做别的操作
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
DiscardOldestPolicy: 放弃最早策略 此策略从任务队列中取出最早的任务丢弃,并重试提交新任务
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
2.Excutors中的线程池
1.newSingleThreadExecutor 单线程执行器
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
2.newFixedThreadPool 固定线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
3.newCachedThreadPool 缓存线程池
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
4.newScheduledThreadPool 预定线程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}