线程池的创建,在Java中给出了几种重载的构造方法,其中参数最多的重载方法如下:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
ThreadPoolExecutorde 的规则如下:
- 创建的线程数小于corePoolSize时,创建的线程均为核心线程;
- corePoolSize<当线程数<maximumPoolSize,创建的线程为非核心线程;
- 当非核心线程的空闲时间大于keepAliveTime时,非核心线程会被销毁;
- 当创建的线程数大于maximumPoolSize时,送来的线程会被放进workQueue中;
- 当workQueue也满了的时候,就会根据RejectedExecutionHandler将线程触发线程拒绝掉。
线程池的几种拒绝策略
RejectedExecutionHandler接口
线程池拒绝策略接口如下:
public interface RejectedExecutionHandler {
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
其中 r为待执行的任务,executor为线程池;
callerRunsPolicy(调用者运行策略)
当触发拒绝策略时,只要线程池没有关闭,就当前任务提交的线程处理;
public static class CallerRunsPolicy implements RejectedExecutionHandler {
public CallerRunsPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}
AbortPolicy(终止策略)
打断当前执行的流程,当触发拒绝策略时,直接抛出拒绝执行的异常,终止当前任务;
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());
}
}
DiscardPolicy(丢弃策略)
直接丢弃这个任务,不会执行任何动作;
public static class DiscardPolicy implements RejectedExecutionHandler {
public DiscardPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
DiscardOldestPolicy(弃老策略)
如果线程池未关闭,就弹出对列头部的任务,尝试执行
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
public DiscardOldestPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}