這是7個參數的JDK源碼:
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;
}
大家可能看了還是有點懵,我來說一個生活中的例子吧~
比如大家去銀行辦理業務,銀行有辦理業務的窗口(有限個),還有提供的座位(讓來辦理業務的客戶等待休息的位置有限個),它的這個辦理業務的窗口並不是什麼時候都全部開放的,還有的情況就是辦理業務的窗口和讓客戶休息的位置全滿了的情況,就會觸發最後一個參數的拒絕策略。
來看這段測試代碼,加深理解:
import java.util.concurrent.*;
public class Test1 {
public static void main(String[] args) {
ExecutorService threadPool = new ThreadPoolExecutor(
2, //核心線程池的大小
5, //最大核心線程池的大小
3, //超時時間(釋放)
TimeUnit.SECONDS,//超時時間的單位
new LinkedBlockingDeque<>(3),//阻塞隊列
Executors.defaultThreadFactory(),//創建線程的工廠
// new ThreadPoolExecutor.AbortPolicy() //拒絕策略 滿了不接待 //java.util.concurrent.RejectedExecutionException:拋出異常
// new ThreadPoolExecutor.CallerRunsPolicy()// main ok 讓ta回去 哪來的去哪 不會拋出異常
// new ThreadPoolExecutor.DiscardPolicy() //隊列滿了 不拋出異常 但是ta會把任務丟掉
new ThreadPoolExecutor.DiscardOldestPolicy()//隊列滿了 ta會嘗試和最早的競爭 (僅僅是嘗試)也沒有異常
);
try {
for (int i = 0; i < 100; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+" ok ");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
關於拒絕策略的深入,大家可以研究下源碼: