线程池的核心参数
- int corePoolSize(核心线程数),默认1
- int maximumPoolSize(最大线程数),默认Integer.MAX_VALUE
- long keepAliveTime(线程空闲存活时间),默认 60s
- TimeUnit unit (存活时间单位),
- BlockingQueue workQueue(队列)
- ThreadFactory threadFactory(创建线程的工厂)
- RejectedExecutionHandler handler(淘汰策略), 默认AbortPolicy()
java提供的线程池方法
- newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
- newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
- newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
- newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
newCachedThreadPool:
- corePoolSize:0
- maximumPoolSize:Integer.MAX_VALUE
- keepAliveTime 60s
- SynchronousQueue
- AbortPolicy
newFixedThreadPool :
- corePoolSize:用户指定
- maximumPoolSize:corePoolSize
- keepAliveTime 0s
- LinkedBlockingQueue
- AbortPolicy
newScheduledThreadPool :
- corePoolSize:用户指定
- maximumPoolSize:Integer.MAX_VALUE
- keepAliveTime 0s
- DelayedWorkQueue
- AbortPolicy
newSingleThreadExecutor:
- corePoolSize:1
- maximumPoolSize:1
- keepAliveTime 0s
- LinkedBlockingQueue
- AbortPolicy
RejectedExecutionHandler
- AbortPolicy : 直接抛出异常,这是默认策略
- CallerRunsPolicy : 用调用者所在线程来执行任务
- DiscardOldestPolicy : 丢弃阻塞队列中最靠前的任务,并执行当前任务
- DiscardPolicy : 直接丢弃任务
注意:
- 线程拒绝策略配置为CallerRunsPolicy、DiscardOldestPolicy、DiscardPolicy时 ,线程池满了不会抛出异常。建议将拒绝策略配置为AbortPolicy
- 一般情况下,代码只会去捕捉Exception,如果抛出Error(比如内存溢出)则会导致线程退出,而异常信息又没有拿到。最佳的解决办法是给线程池设置UncaughtExceptionHandler
阻塞队列
- ArrayBlockingQueue :一个由数组支持的有界队列。
- LinkedBlockingQueue :一个由链接节点支持的可选有界队列。
- PriorityBlockingQueue :一个由优先级堆支持的无界优先级队列。
- DelayQueue :一个由优先级堆支持的、基于时间的调度队列。
- SynchronousQueue :一个利用 BlockingQueue 接口的简单聚集(rendezvous)机制。
LinkedBlockingQueue:
的容量是没有上限的(说的不准确,在不指定时容量为Integer.MAX_VALUE,不要然的话在put时怎么会受阻呢),但是也可以选择指定其最大容量,它是基于链表的队列,此队列按 FIFO(先进先出)排序元素。
ArrayBlockingQueue:
在构造时需要指定容量, 并可以选择是否需要公平性,如果公平参数被设置true,等待时间最长的线程会优先得到处理(其实就是通过将ReentrantLock设置为true来 达到这种公平性的:即等待时间最长的线程会先操作)。通常,公平性会使你在性能上付出代价,只有在的确非常需要的时候再使用它。它是基于数组的阻塞循环队 列,此队列按 FIFO(先进先出)原则对元素进行排序。
PriorityBlockingQueue:
是一个带优先级的 队列,而不是先进先出队列。元素按优先级顺序被移除,该队列也没有上限(看了一下源码,PriorityBlockingQueue是对 PriorityQueue的再次包装,是基于堆数据结构的,而PriorityQueue是没有容量限制的,与ArrayList一样,所以在优先阻塞 队列上put时是不会受阻的。虽然此队列逻辑上是无界的,但是由于资源被耗尽,所以试图执行添加操作可能会导致 OutOfMemoryError),但是如果队列为空,那么取元素的操作take就会阻塞,所以它的检索操作take是受阻的。另外,往入该队列中的元 素要具有比较能力。
DelayQueue:
(基于PriorityQueue来实现的)是一个存放Delayed 元素的无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的头部是延迟期满后保存时间最长的 Delayed 元素。如果延迟都还没有期满,则队列没有头部,并且poll将返回null。当一个元素的 getDelay(TimeUnit.NANOSECONDS) 方法返回一个小于或等于零的值时,则出现期满,poll就以移除这个元素了。此队列不允许使用 null 元素。
阻塞队列的操作
- add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常,调用offer()
- remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常,调用poll()
- element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常,调用peek()
- offer 添加一个元素并返回true 如果队列已满,则返回false
- poll 移除并返问队列头部的元素 如果队列为空,则返回null
- peek 返回队列头部的元素 如果队列为空,则返回null
- put 添加一个元素 如果队列满,则阻塞
- take 移除并返回队列头部的元素 如果队列为空,则阻塞
ArrayBlockingQueue
初始化的参数
- int capacity 队列大小
- boolean fair 是否是公平队列
offer()方法:
public boolean offer(E e) {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count == items.length)
return false;
else {
enqueue(e);
return true;
}
} finally {
lock.unlock();
}
}
有等待时间的offer():
/**
* Inserts the specified element at the tail of this queue, waiting
* up to the specified wait time for space to become available if
* the queue is full.
*
* @throws InterruptedException {@inheritDoc}
* @throws NullPointerException {@inheritDoc}
*/
public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
checkNotNull(e);
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length) {
if (nanos <= 0)
return false;
nanos = notFull.awaitNanos(nanos);
}
enqueue(e);
return true;
} finally {
lock.unlock();
}
}
poll方法:
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (count == 0) ? null : dequeue();
} finally {
lock.unlock();
}
}
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0) {
if (nanos <= 0)
return null;
nanos = notEmpty.awaitNanos(nanos);
}
return dequeue();
} finally {
lock.unlock();
}
}
peek()方法
public E peek() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return itemAt(takeIndex); // null when queue is empty
} finally {
lock.unlock();
}
}
put()方法
public void put(E e) throws InterruptedException {
checkNotNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length)
notFull.await();
enqueue(e);
} finally {
lock.unlock();
}
}
take()方法:
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}