策略模式
多线程中的拒绝策略
在使用java多线程时,我们一般使用Executors类去产生一项线程池,但是这个类中的方法最后使用的是ThreadPoolExecutor中的构造函数进行初始化。其中的ThreadFactory与RejectedExecutionHandler就可以看作是策略模式。
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
ThreadFactory与RejectedExecutionHandler,是两个接口,一个用于产生线程,一个是当任务超过workQueue后,任务的处理方式。
比如RejectedExecutionHandler当前有四种实现方式:
- AbortPolicy:超出时,直接抛出异常
- CallerRunsPolicy:在调用线程(即主线程)中立即执行该任务的run方法
- DiscardOldestPolicy:丢弃最老的任务
- DiscardPolicy:丢弃当前任务
策略模式类图
上面是一个简单的策略模式,一个完整的策略模式,结构如下:
其中Context相当于ThreadPoolExecutor,Strategy是它的一部分吧。