處理被拒絕的執行
如果
- 你嘗試將任務提交給關閉 Executor 或
- 佇列已飽和(僅限有限佇列)並且已達到最大執行緒數,
RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor)
將被召喚。
預設行為是你將在呼叫者處丟擲 RejectedExecutionException。但是有更多預定義的行為可用:
- ThreadPoolExecutor.AbortPolicy (預設情況下,將丟擲 REE)
- ThreadPoolExecutor.CallerRunsPolicy (在呼叫者的執行緒上執行任務 - 阻止它 )
- ThreadPoolExecutor.DiscardPolicy (靜默丟棄任務)
- ThreadPoolExecutor.DiscardOldestPolicy (以靜默方式丟棄佇列中最舊的任務並重試執行新任務)
你可以使用其中一個 ThreadPool 建構函式設定它們 :
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) // <--
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) // <--
你還可以通過擴充套件 RejectedExecutionHandler 介面來實現自己的行為 :
void rejectedExecution(Runnable r, ThreadPoolExecutor executor)