ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("xxx-thread-%d").build();
ExecutorService executor = new ThreadPoolExecutor(16,
32,
60000L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(200),
namedThreadFactory,
new DiscardOldestPolicy());
複製代碼
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.acc = System.getSecurityManager() == null ? null : AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
複製代碼
保持在池中的線程數,即便它們是空閒的; 設置{@code allowCoreThreadTimeOut},容許線程數低於corePoolSize時,線程也由於空閒而終止。java
池中容許的最大線程數bash
當線程數大於corePoolSize時,多餘的空閒線程等待新任務的最大時間,超過此時間會被回收。ide
keepAliveTime的時間單位函數
用於在任務執行前保存任務的隊列。這個隊列將只包含{@code execute}方法提交的{@code Runnable}任務。ui
執行程序建立新線程時使用的線程工廠this
RejectedExecutionHandler(飽和策略):當隊列和線程池都滿了,說明線程池處於飽和狀態,那麼必須採起一種策略處理提交的新任務。spa
默認的飽和策略,直接拋出java.util.concurrent.RejectedExecutionException異常
複製代碼
任務被拒絕添加後,會調用當前線程池的所在的線程去執行被拒絕的任務。這個策略的缺陷就是可能會阻塞主線程。
複製代碼
讓被線程池拒絕的任務直接拋棄,不會拋異常也不會執行。
複製代碼
當任務被拒絕添加時,會拋棄任務隊列中最早加入隊列的,再把這個新任務添加進去。
複製代碼
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author
* @version 1.0.0
* @Description 捨棄隊列中最早加入的五條任務,並將新的任務加入隊尾
* @date 2020/6/2 21:25
* @since 1.8
*/
public class MyRejectedPolicy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (!executor.isShutdown()){
executor.getQueue().poll();
executor.getQueue().poll();
executor.getQueue().poll();
executor.getQueue().poll();
executor.getQueue().poll();
executor.getQueue().offer(r);
}
}
}
複製代碼