取消和关闭:java
任务取消:this
为何须要取消? 用户请求取消、有时间限制的事件、运行中发生错误。线程
取消策略:其余代码如何(how)取消,任务在什么时候(when)检查是否已经请求了取消,另外响应请求时该执行哪些策略(what)。code
中断是实现取消的最合理方式。blog
中断策略:中断策略规定线程如何解释某个中断请求--当发生中断请求时,应该作哪些工做,哪些工做单元对于中断来讲是原子操做,以及以多快的速度来响应中断。接口
线程池的使用:队列
ThreadPoolExector事件
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; }
corePoolSize | 核心线程池大小 |
maximumPoolSize | 最大线程池大小 |
keepAliveTime | 线程池中超过corePoolSize数目的空闲线程最大存活时间;能够allowCoreThreadTimeOut(true)使得核心线程有效时间 |
TimeUnit | keepAliveTime时间单位 |
workQueue | 阻塞任务队列 |
threadFactory | 新建线程工厂 |
RejectedExecutionHandler | 当提交任务数超过maxmumPoolSize+workQueue之和时,任务会交给RejectedExecutionHandler来处理 |
其中比较容易让人误解的是:corePoolSize,maximumPoolSize,workQueue之间关系。
1.当线程池小于corePoolSize时,新提交任务将建立一个新线程执行任务,即便此时线程池中存在空闲线程。
2.当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行
3.当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会建立新线程执行任务
4.当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理
5.当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程
6.当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭 it
参考:http://825635381.iteye.com/blog/2184680io
当队列已满,而且达到maximumPoolSize时,饱和策略开始发挥做用。
实现RejectedExecutionHandler接口来配置饱和策略。
饱和策略:AbortPolicy(停止)、CallerRunsPolicy(调用者运行)、DiscardPolicy()等。
线程工程 ThreadFactory
每当线程池须要建立一个线程时,都是经过线程工厂方法建立的。