重写线程池

什么是线程池

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

  • 依赖性任务
  • 对响应时间敏感的任务
  • 使用了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:
* {@code corePoolSize < 0}
* {@code keepAliveTime < 0}
* {@code maximumPoolSize <= 0}
* {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} * or {@code threadFactory} is null */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue 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()));
    }

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

    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 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 workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

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

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

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


}

你可能感兴趣的:(重写线程池)