线程池的拒绝策略
线程池的构造方法
public ThreadPoolExecutor(int corePoolSize, //核心线程池大小
int maximumPoolSize, //最大线程池大小
long keepAliveTime, //超出核心线程池的线程存活时间
TimeUnit unit, //存活时间单位
BlockingQueue<Runnable> workQueue, //阻塞队列
ThreadFactory threadFactory, //创建工厂
RejectedExecutionHandler handler) //拒绝策略
RejectedExecutionHandler 接口就是拒绝策略的类,实现该接口即可创建自定义的线程池拒绝策略。
public interface RejectedExecutionHandler {
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
jdk自定义的拒绝策略:
AbortPolicy(默认) 抛出异常。
DiscardOldestPolicy 丢弃队列中最前面的任务,execute该线程。进入队列。(有优先级的)
DiscardPolicy 丢弃。 方法为空,直接不处理。(不重要的任务)
CallerRunsPolicy 当前线程直接执行run方法。(不允许失败)
具体代码时间也是简单
public static class AbortPolicy implements RejectedExecutionHandler {
public AbortPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
public static class DiscardPolicy implements RejectedExecutionHandler {
public DiscardPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
public DiscardOldestPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
//丢弃队列头的线程
e.getQueue().poll();
//执行该线程
e.execute(r);
}
}
}
public static class CallerRunsPolicy implements RejectedExecutionHandler {
public CallerRunsPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}
一些开源框架的自定义线程池