為什么要使用拒絕策略?
等待隊(duì)列已經(jīng)排滿了,再也塞不下新任務(wù)了
同時(shí),線程池中的max線程也達(dá)到了,無法繼續(xù)為新任務(wù)服務(wù)。
這個(gè)是時(shí)候我們就需要拒絕策略機(jī)制合理的處理這個(gè)問題。
四種拒絕策略介紹
jdk中自帶的拒絕策略均實(shí)現(xiàn)了java.util.concurrent.RejectedExecutionHandler接口
AbortPolicy
默認(rèn)的拒絕策略。直接拋出 java.util.concurrent.RejectedExecutionException異常
new ThreadPoolExecutor.AbortPolicy()
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(2, 5, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 辦理業(yè)務(wù)");
}
});
}
} finally {
executorService.shutdown();
}
}
}
CallerRunsPolicy
將任務(wù)返還給調(diào)用者線程執(zhí)行
new ThreadPoolExecutor.CallerRunsPolicy()
import java.util.concurrent.*;
public class Test {
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(2, 5, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
try {
for (int i = 1; i <= 9; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 辦理業(yè)務(wù)");
}
});
}
} finally {
executorService.shutdown();
}
}
}
執(zhí)行結(jié)果: 任務(wù)果然返還給main線程了

image.png
DiscardPolicy
直接拋棄無法處理的任務(wù),不予處理不拋異常。如果業(yè)務(wù)匯總允許任務(wù)丟失,這是最好的策略
new ThreadPoolExecutor.DiscardPolicy()
查看執(zhí)行結(jié)果,只有8個(gè)。第9個(gè)被拋棄

image.png
DiscardOldestPolicy
拋棄隊(duì)列中等待最久的任務(wù),然后把當(dāng)前任務(wù)加入隊(duì)列中嘗試再次提交當(dāng)前任務(wù)
new ThreadPoolExecutor.DiscardOldestPolicy()

image.png