美文网首页
重写线程池

重写线程池

作者: 我是陈炜 | 来源:发表于2020-04-05 18:25 被阅读0次

什么是线程池

线程池 我们都知道 是一种池化技术,主要解决了线程创建都额外资源消耗,线程监控 等问题 当然 线程池不适用于以下几种情况

  • 依赖性任务
  • 对响应时间敏感的任务
  • 使用了ThreadLocal 且不remove的任务

线程池核心参数


    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default rejected execution handler.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }
翻译
  • corePoolSize 正常情况下 线程池的工作线程数
  • maximumPoolSize 等待队列已经排满的情况下 线程池的最大工作线程数
  • keepAliveTime 如果工作线程数 大于corePoolSize 情况下 空闲线程的回收等待时间
  • unit keepAliveTime的单位
  • workQueue 线程池的线程为corePoolSize的情况下 线程的等待队列
  • threadFactory 线程池 创建工作线程的线程工厂

常用线程池创建手段

我们常用的线程池框架 为Executor 创建的线程池方式大致有以下几种

newCachedThreadPool

newCachedThreadPool 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。


newCachedThreadPool

这种方式会导致max工作线程数是Integer.maxValue 极端情况下 可能会导致服务器奔溃。

newFixedThreadPool

newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。


newFixedThreadPool

这种方式创建的核心工作线程数和最大工作线程数是较为合理的

newScheduledThreadPool

newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。

    public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1));
    }
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

很明显 newScheduledThreadPool 这种方式 虽然设置了一个延时队列 ,但是极端情况下 仍然会让服务奔溃

newSingleThreadExecutor

newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

综上所述 我们最好是自己设置参数 来生成自己的线程池

    private static ExecutorService taskExecutor = new ThreadPoolExecutor(
            MAX_THREAD_COUNT, MAX_THREAD_COUNT, 60, TimeUnit.SECONDS, taskQueue);

重写一个属于我们的线程池

如果 我们希望能自定义一些aop的方法。那么 我们可以通过重写线程池来实现 例子如下 其中 before

package pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @description:
 * @author: brave.chen
 * @create: 2020-04-05 17:51
 **/
public class MyDesignThreadPool extends ThreadPoolExecutor {


    private final ThreadLocal<Long> startTime = new ThreadLocal<>();
    private final Logger logger = LoggerFactory.getLogger(MyDesignThreadPool.class);
    private final AtomicInteger numTasks = new AtomicInteger();
    private final AtomicLong totalTime = new AtomicLong();

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        logger.info("Thread " + t + " : start  " + r);
        startTime.set(System.nanoTime());
        super.beforeExecute(t, r);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        try {
            long endTime = System.nanoTime();
            long taskTime = endTime - startTime.get();
            numTasks.incrementAndGet();
            totalTime.addAndGet(taskTime);
            logger.info("Thread " + t + " : end  " + endTime + ", time = " + taskTime);
        } finally {
            super.afterExecute(r, t);
        }
    }

    @Override
    protected void terminated() {
        try {
            logger.info("Terminated : avg time = " + totalTime.get()/numTasks.get() );
        }finally {
            super.terminated();
        }
    }

    public MyDesignThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public MyDesignThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    public MyDesignThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    }

    public MyDesignThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }


}

相关文章

  • 重写线程池

    什么是线程池 线程池 我们都知道 是一种池化技术,主要解决了线程创建都额外资源消耗,线程监控 等问题 当然 线程...

  • Android 面试主题集合整理

    一、线程、多线程和线程池面试专题 1、开启线程的三种方式? 1)继承 Thread 类,重写 run()方法,在 ...

  • Springboot 异步线程示例

    定义线程池 @EnableAsync 注解开开启异步。 实现 AsyncConfigurer,重写 getAsyn...

  • 十分钟了解Java并发编程

    线程、线程池、锁、线程通信、数据结构 一、线程 线程的实现方式有三种(重写Thread的run方法、实现Runna...

  • 线程池系列(4)tomcat实现ThreadPoolExecut

    高频面试题:tomcat的线程池和JDK的线程池有什么区别?解答这个问题前,我们需要分析下tomcat如何重写JD...

  • JAVA 线程池(四)异常捕获

    重写ThreadPoolExecutor的afterExecute方法 、如果是定时器线程池就用TryCatch...

  • 多线程应用场景

    多线程运行定时任务: 重写Spring定时器线程池,每次使用时根据注解@Scheduled(cron = "0 0...

  • 重写并优化 ThreadPoolExecutor 线程池

    import java.util.concurrent.*;import java.util.concurrent...

  • java线程池

    线程VS线程池 普通线程使用 创建线程池 执行任务 执行完毕,释放线程对象 线程池 创建线程池 拿线程池线程去执行...

  • java----线程池

    什么是线程池 为什么要使用线程池 线程池的处理逻辑 如何使用线程池 如何合理配置线程池的大小 结语 什么是线程池 ...

网友评论

      本文标题:重写线程池

      本文链接:https://www.haomeiwen.com/subject/gifpphtx.html