ThreadPoolExecutor
1、构造方法
- corePoolSize : 核心线程数
- maximumPoolSize : 最大线程数量
- keepAliveTime : 空闲存活时间
- unit :时间单位
- workQueue :阻塞队列,用来存储等待执行的任务。
- ArrayBlockingQueue:数组有界队列,先进先出
- DelayQueue : 无界阻塞队列,延迟期满才能提取元素
- LinkedBlockingQueue:链式结构,先进先出
- PriorityBlockingQueue:支持优先级排序的无界队列,可以自定义实现compareTo()方法指定元素排序。不能保证优先级元素的顺序
- SynchronousQueue :容纳单元素
- BlockingDeque :双端队列,在不能够插入元素的时候,阻塞插入。没有元素抽取的时候,阻塞抽取。
- LinkedBlockingDeque:是双向链表实现的双向并发阻塞队列。该阻塞队列同时支持FIFO和FILO两种操作方式,即可以从队列的头和尾同时操作(插入/删除);并且,该阻塞队列是支持线程安全。此外,LinkedBlockingDeque还是可选容量的(防止过度膨胀),即可以指定队列的容量。如果不指定,默认容量大小等于Integer.MAX_VALUE
- threadFactory:线程工厂,用来创建线程
- handler :饱和策略
- CallerRunsPolicy:用调用者所在的线程来执行任务
- AbortPolicy :默认策略,直接抛出异常
- DiscardPolicy :直接丢弃任务
- DiscardOldestPolicy:丢弃队列最前的任务,并执行当前任务
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;
}
2、execute方法
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); /* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn't, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */ int c = ctl.get(); if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } else if (!addWorker(command, false)) reject(command); }