Java8中的ThreadPoolExecutor

本文介绍了Java8中ThreadPoolExecutor的使用,包括如何创建线程池、核心参数解析及线程池拒绝策略。强调了FixedThreadPool和SingleThreadExecutor可能导致的内存问题,推荐使用ThreadPoolExecutor,并提醒注意线程池参数的合理配置以避免IllegalArgumentException和NullPointerException。同时,讨论了自定义ThreadFactory和RejectedExecutionHandler的重要性,以及四种常见的拒绝策略:AbortPolicy、CallerRunsPolicy、DiscardPolicy和DiscardOlderPolicy。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于线程池的创建,可以直接使用Executor所属的方法来创建,代码如下。

	//可重用固定个数线程池,以共享的无界队列方式来运行这些线程
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(int n);

    //可缓存线程池
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    //单线程化线程池,只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
    ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();

    //定长线程池,支持定时以及周期性任务执行
    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(int n);

需要注意的是,虽然这四种线程池都属于java.util.concurrent包下,但是ScheduledThreadPool和其他三种线程池不在同一个包下,代码如下

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

其中,FixedThreadPool以及SingleThreadExecutor可能会造成大量的请求堆积,导致OOM
CachedThreadPool和ScheduledThreadPool可能会创建大量的线程,导致OOM
所以推荐使用的还是ThreadPoolExecutor
一般来讲我们使用的都是默认的ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue)

在Java8中源码如下:

/**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory and rejected execution handler.
     * It may be more convenient to use one of the {@link Executors} factory
     * methods instead of this general purpose constructor.
     *
     * @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.
     * @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} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

从注释说明中可以看到,使用ThreadPoolExecutor时,会使用默认的thread factory和拒绝策略
然后就是建议直接使用Executors的方法,所以可以忽略这句话

具体的参数说明为:
corePoolSize:线程池中需要保持的线程数量,即使他们是闲置的状态,除非设置allowCoreThreadTimeOut
maximumPoolSize:线程池中允许的最大数量
keepAliveTime:corePoolSize中的线程之外的等待线程,最大等待时间
unit:keepAliveTime的时间单位
workQueue:执行前的等待队列,可以用Runnable的execute方法运行

需要注意的是:
(1)corePoolSize、keepAliveTime不能小于0
maximumPoolSize不能小于等于0
maximumPoolSize不能小于corePoolSize

否则会出现IllegalArgumentException

(2)workQueue不能为空

否则会出现NullPointerException

其中ThreadFactory和RejectedExecutionHandler也可以两个都自定义,也可以只自定义ThreadFactory,使用默认的RejectedExecutionHandler,并且在完全自定以的源码中会更直观的看到参数的范围等。

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

线程池的拒绝策略:
AbortPolicy,终止策略,报出异常并终止运行(默认的拒绝策略)
CallerRunsPolicy,把任务交给当前线程来运行
DiscardPolicy,忽略此次任务(最新的任务)
DiscardOlderPolicy,忽略最早的任务(最先加入队列的任务)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值