取消和關閉: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
每當線程池須要建立一個線程時,都是經過線程工廠方法建立的。