引子问题
问题1:什么时候触发拒绝策略?
问题2:拒绝策略有哪些?
问题3:默认的拒绝策略是什么?
问题4:你实际开发经历中的拒绝策略是什么?
创建线程池
核心线程数、最大线程数、空闲存活时间根据业务决定
任务队列避免使用无界队列,以免产生OOM
int coreSize = 4;
int maximumPoolSize = 8;
long keepAliveTime = 5;
TimeUnit unit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(20);
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
ThreadPoolExecutor pool = new ThreadPoolExecutor(coreSize,maximumPoolSize,keepAliveTime,unit,workQueue,handler);
拒绝策略有哪些
严格来说,只要实现了RejectedExecutionHandler接口的,都可以作为拒绝策略,这里讨论的是JUC自带的拒绝策略。
上源码……
package java.util.concurrent;
/**
* A handler for tasks that cannot be executed by a {@link ThreadPoolExecutor}.
*
* @since 1.5
* @author Doug Lea
*/
public interface RejectedExecutionHandler {
/**
* Method that may be invoked by a {@link ThreadPoolExecutor} when
* {@link ThreadPoolExecutor#execute execute} cannot accept a
* task. This may occur when no more threads or queue slots are
* available because their bounds would be exceeded, or upon
* shutdown of