我已經閱讀從Java文檔手動約ThreadPoolExecutor
:爲什麼拒絕處理程序不調用時隊列溢出和繁忙的所有線程
讓我們來看看這部分:
拒絕任務的
在執行方法execute(java.lang.Runnable)中提交的新任務將爲 當Executor已關閉時被拒絕,還有whe 執行器對最大線程和工作隊列使用有限邊界容量,並且是飽和的。無論哪種情況,execute方法都會調用 RejectedExecutionHandler的RejectedExecutionHandler.rejectedExecution(java.lang.Runnable, java.util.concurrent.ThreadPoolExecutor)方法 。四種預定義的處理程序策略提供 :
- 在默認ThreadPoolExecutor.AbortPolicy,處理程序拒絕時拋出一個 運行時RejectedExecutionException。
- 在ThreadPoolExecutor.CallerRunsPolicy中,調用 執行的線程運行該任務。這提供了一個簡單的反饋 控制機制,將減慢提交新任務 的速度。
- 在ThreadPoolExecutor.DiscardPolicy中,無法執行 的任務將被簡單刪除。
- 在ThreadPoolExecutor.DiscardOldestPolicy,如果 執行不關閉,在工作隊列頭部的任務是 掉線,然後執行重試(可再次失敗, 導致此重複。) 可以定義和使用其他種類的RejectedExecutionHandler類。這樣做需要特別小心,特別是當策略只能在特定的容量或排隊策略下工作時。
要檢查黑體字我試着寫小例子:
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(1),
Executors.defaultThreadFactory(),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("rejected");
}
});
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("work started");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("work finished");
}
};
//execute
threadPoolExecutor.execute(runnable);
threadPoolExecutor.execute(runnable);
threadPoolExecutor.shutdown();
這段代碼輸出:
work started
work finished
work started
work finished
我期望看到 「拒絕」,在控制檯輸出。
你能解釋這種行爲嗎?