线程池工厂类
public class MyThreadPoolFactory{
//核心线程数
private static final Integer CORE_POOL_SIZE = 8;
//最大线程数
private static final Integer MAX_POOL_SIZE = 12;
//空闲线程存活时间
private static final Integer KEEP_ALIVE = 60;
//任务队列大小
private static final Integer QUEUE_SIZE = 128;
//自定义拒绝策略
private static final RejectedExecutionHandler REJECTED_HANDLER = new MyRejectedExecutionHandle;
//线程名
private static final String POOL_NAME ='我的线程';
//线程池对象
private ThreadPoolExcutor excutor;
//工厂实例
private static volatile MyThreadPoolFactory instance;
private MyThreadPoolFactory(Integer coolPoolSize, Integer maxPoolSize, Integer keepAliveTime, TimeUnit timeUnit,
Integer taskQueueSize, ThreadFactory threadFactory, RejectedExecutionHandler handler){
this.executor = new ThreadPoolExecutor(coolPoolSize, maxPoolSize, keepAliveTime, timeUnit,
new LinkedBlockingQueue<>(taskQueueSize), threadFactory, handler);
}
public static MyThreadPoolFactory getInstance() {
if (null == instance) {
synchronized (MyThreadPoolFactory.class) {
if (null == instance) {
instance = new MyThreadPoolFactory(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAX_POOL_SIZE, DEFAULT_FREE_THREAD_KEEP_ALIVE,
TimeUnit.SECONDS, DEFAULT_TASK_QUEUE_SIZE, new CustomizableThreadFactory(THREAD_POOL_PRE_NAME), DEFAULT_
}
}
}
/**
* 获取executor对象
* @return
*/
public static ThreadPoolExecutor getExecutor(){
return getInstance().executor;
}
}
自定义决绝策略
public static class LogPolicy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
ThreadFactory factory = executor.getThreadFactory();
String threadNamePrefix = "";
if (factory.getClass() == CustomizableThreadFactory.class) {
CustomizableThreadFactory factory1 = (CustomizableThreadFactory) factory;
threadNamePrefix = factory1.getThreadNamePrefix();
}
log.error("threadNamePrefix"};
}
}
调用
MyThreadPoolFactory.getExecutor().execute(()->serivce.doSomething());