当前位置 博文首页 > asd1358355022的博客:每日积累【Day 6】Java线程池重温 Part 3

    asd1358355022的博客:每日积累【Day 6】Java线程池重温 Part 3

    作者:[db:作者] 时间:2021-07-25 12:33

    Java线程池重温 Part 3:线程池原理剖析(Part 1)

    书接上文:https://blog.csdn.net/asd1358355022/article/details/118947919
    书接上上文:https://blog.csdn.net/asd1358355022/article/details/118885688

    12、线程池中的参数介绍

    代码实现部分

    /**
         * Creates a new {@code ThreadPoolExecutor} with the given initial
         * parameters.
         *
         * @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
         * @param handler the handler to use when execution is blocked
         *        because the thread bounds and queue capacities are reached
         * @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} or {@code handler} is null
         */
        public ThreadPoolExecutor(int corePoolSize,
                                  int maximumPoolSize,
                                  long keepAliveTime,
                                  TimeUnit unit,
                                  BlockingQueue<Runnable> workQueue,
                                  ThreadFactory threadFactory,
                                  RejectedExecutionHandler handler) {
        //.............内部实现..............省略
        }
    

    ? corePoolSize:核心线程数,在线程池种常驻,除非设置了allowCoreThreadTimeOut参数

    ? maximumPoolSize:线程池种总计的线程数量(核心线程数量+非核心线程数量),一般maximumPoolSize>=corePoolSize;【例如maximumPoolSize=20,corePoolSize=10,我们有20个任务要执行,那我们会优先使用10个核心线程,再创建10个非核心线程去执行任务】

    ? keepAliveTime:非核心线程在空闲的时候,一个存活时间,超过存活时间的空闲非核心线程被清理掉

    ? unit:keepAliveTime参数的时间单位,给非核心线程设置存活时间

    ? workQueue: 工作队列用于在任务完成之前保存任务的队列

    ? threadFactory:工作队列在执行任务之前用于保存任务的队列。这个队列将只保存由{@code execute}方法提交的{@code Runnable}任务

    ? handler: handler由于达到线程边界和队列容量而阻止执行时要使用的处理程序 (当核心线程非核心线程都繁忙,工作队列已满的情况下执行的拒绝处理)

    13、五种线程池的使用姿势

    **1、Executors.newSingleThreadExecutor():**创建一个单线程的线程池,此线程池保证所有任务的执行顺

    序按 照任务的提交顺序执行。

    码实现部分

    	/**
         * Creates an Executor that uses a single worker thread operating
         * off an unbounded queue. (Note however that if this single
         * thread terminates due to a failure during execution prior to
         * shutdown, a new one will take its place if needed to execute
         * subsequent tasks.)  Tasks are guaranteed to execute
         * sequentially, and no more than one task will be active at any
         * given time. Unlike the otherwise equivalent
         * {@code newFixedThreadPool(1)} the returned executor is
         * guaranteed not to be reconfigurable to use additional threads.
         *
         * @return the newly created single-threaded Executor
         */
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
    

    适应场景:适用于需要保证任务顺序执行,并且在任意时间点不会有多个线程活动的场景。

    **2、Executors.newFixedThreadPool(int n):**创建固定线程数量的线程池,该线程池中的线程数量保

    持不变。当有新任务提交时,线程池中若有空闲线程,则立即执行;若没有,则新的任务会被暂

    存在一个任务队列中,待有线程空闲时,便处理任务队列中的任务。

    适应场景:适用于为了满足资源管理需求,而需要限制当前线程的数量的应用场景,它适用于负 载比较重的服务器。

    代码实现部分

    	 /**
         * Creates a thread pool that reuses a fixed number of threads
         * operating off a shared unbounded queue.  At any point, at most
         * {@code nThreads} threads will be active processing tasks.
         * If additional tasks are submitted when all threads are active,
         * they will wait in the queue until a thread is available.
         * If any thread terminates due to a failure during execution
         * prior to shutdown, a new one will take its place if needed to
         * execute subsequent tasks.  The threads in the pool will exist
         * until it is explicitly {@link ExecutorService#shutdown shutdown}.
         *
         * @param nThreads the number of threads in the pool
         * @return the newly created thread pool
         * @throws IllegalArgumentException if {@code nThreads <= 0}
         */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
    

    **3、Executors.newCachedThreadPool():**创建一个可以根据实际情况调整线程数量的线程池,线程池中

    的线程数量不确定。若有空闲的线程可以复用,则会优先使用可复用的线程;若所有线程都在工

    作,又有新的任务提交,则会创建新的线程处理任务,没有个数上限。

    适应场景:大小无界的线程池,适用于执行很多的短期任务的小程序,或者负载较轻的服务器。

    代码实现部分

    	/**
         * Creates a thread pool that creates new threads as needed, but
         * will reuse previously constructed threads when they are
         * available.  These pools will typically improve the performance
         * of programs that execute many short-lived asynchronous tasks.
         * Calls to {@code execute} will reuse previously constructed
         * threads if available. If no existing thread is available, a new
         * thread will be created and added to the pool. Threads that have
         * not been used for sixty seconds are terminated and removed from
         * the cache. Thus, a pool that remains idle for long enough will
         * not consume any resources. Note that pools with similar
         * properties but different details (for example, timeout parameters)
         * may be created using {@link ThreadPoolExecutor} constructors.
         *
         * @return the newly created thread pool
         */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    

    **4、Executors.newScheduledThreadPool(int n):**创建一个定长线程池,支持定时及周期性任务执行

    代码实现部分

     /**
         * Creates a new {@code ScheduledThreadPoolExecutor} with the
         * given core pool size.
         *
         * @param corePoolSize the number of threads to keep in the pool, even
         *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
         * @throws IllegalArgumentException if {@code corePoolSize < 0}
         */
        public ScheduledThreadPoolExecutor(int corePoolSize) {
            super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                  new DelayedWorkQueue());
        }
    

    5、自定义线程池:

    new ThreadPoolExecutor(10, 20, 100L, TimeUnit.SECONDS, (BlockingQueue<Runnable>) new WorkQueueImpl());
    

    14、不建议使用Executors创建线程池的原因

    从上面列举中我们可以看出来前四种创建线程的方式是由jdk中提供的工具包封装好的工具类创建的,阿里并不推荐大家直接去使用这个Executors去创建使用线程池,原因如下:

    1、ScheduledThreadPool和CachedThreadPool的maximumPoolSize参数(允许最大线程数)为Integer.MAX_VALUE,会有OOM的风险

    2、SingleThreadExecutor和FixedThreadPool的workQueue参数(工作队列)容量为Integer.MAX_VALUE,会有OOM的风险

    建议使用自定义线程池。(结合业务场景去设置自定义线程池的参数)

    15、线程池原理图:(部分)

    这是我画的略微粗糙的图,凑乎看哈哈

    线程池执行execute,提交任务时的场景:对比右边执行execute方法代码理解图示

    在这里插入图片描述

    工作较忙,持续更新中。。。。。。

    cs