一个简单的线程池

文章介绍了如何创建一个自定义的线程池工厂类,包括设置核心线程数、最大线程数、空闲线程存活时间和任务队列大小。此外,还定义了一个特殊的拒绝执行策略,当任务无法接受时,会在日志中记录相关信息。
摘要由CSDN通过智能技术生成

线程池工厂类

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());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值