Java 線程池的拒絕策略 RejectedExecutorHandler

當線程池被關閉以後,在execute()方法中提交新任務將被拒絕(線程池被關閉或線程數達到maximumPoolSize),此時會採取定義的拒絕策略。在ThreadPoolExecutor中定義了四個靜態內部類,均實現了RejectedExecutorService接口,並對接口中的rejectedExecution方法給出具體實現。

一、CallerRunsPolicy

如果線程池沒有被關閉,則由提交該任務的線程來執行

public static class CallerRunsPolicy implements RejectedExecutionHandler {
	public CallerRunsPolicy() { }

	public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
		if (!e.isShutdown()) {
			r.run();
		}
	}
}

二、AbortPolicy

默認的拒絕策略,直接拋出RejectedExecutionException異常。

public static class AbortPolicy implements RejectedExecutionHandler {
	public AbortPolicy() { }

	public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
		throw new RejectedExecutionException("Task " + r.toString() +
											 " rejected from " +
											 e.toString());
	}
}

三、DiscardPolicy

什麼都不做,直接丟棄被拒絕的任務

public static class DiscardPolicy implements RejectedExecutionHandler {
	public DiscardPolicy() { }

	public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
	}
}

四、DiscardOldestPolicy

如果線程池沒有被關閉,則丟棄隊列首部的任務,提交這個新的任務

public static class DiscardOldestPolicy implements RejectedExecutionHandler {
	public DiscardOldestPolicy() { }

	public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
		if (!e.isShutdown()) {
			e.getQueue().poll();
			e.execute(r);
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章