线程池的拒绝策略

默认提供4种拒绝策略,可以自定义实现RejectedExecutionHandler进行扩展

1、AbortPolicy

2、DiscardPolicy 

3、DiscardOldestPolicy 

4、CallerRunsPolicy 


AbortPolicy,无法处理任务任务的时候,直接抛出异常,

public static class AbortPolicy implements RejectedExecutionHandler {
    /**
     * Creates an <tt>AbortPolicy</tt>.
     */
    public AbortPolicy() { }
 
    /**
     * Always throws RejectedExecutionException.
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     * @throws RejectedExecutionException always.
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        throw new RejectedExecutionException();
    }
}

DiscardPolicy 丢弃当前将要加入队列的任务本身

public static class DiscardPolicy implements RejectedExecutionHandler {
    /**
     * Creates a <tt>DiscardPolicy</tt>.
     */
    public DiscardPolicy() { }
 
    /**
     * 不做任何处理,直接丢弃掉当前任务  
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    }
}

DiscardOldestPolicy 丢弃任务队列中最旧任务

public static class DiscardOldestPolicy implements RejectedExecutionHandler {
    /**
     * Creates a <tt>DiscardOldestPolicy</tt> for the given executor.
     */
    public DiscardOldestPolicy() { }
 
    /**
     * 丢弃任务队列中掉最的任务,然后将当前任务重新执行
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            e.getQueue().poll();
            e.execute(r);
        }
    }
}

CallerRunsPolicy 由调用者线程去执行,在任务提交速度过快的情况,可减少任务提交的速度,同时可以保证任务的执行。

public static class CallerRunsPolicy implements RejectedExecutionHandler {
    /**
     * Creates a <tt>CallerRunsPolicy</tt>.
     */
    public CallerRunsPolicy() { }
 
    /**
     * 由调用者自身的线程取执行
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            r.run();
        }
    }
}