线程池的使用

线程池参数


/**
     * 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) {
      
    }
  1. corePoolSize 核心线程池大小

  2. maximumPoolSize 线程池最大容量

  3. keepAliveTime

    当线程池数量超过核心线程池大小时,线程的空闲时间大于keepAliveTime则要被终止,直到小于CorePoolSize

  4. TimeUnit 时间单位

  5. workQueue 阻塞队列

    ArrayBlockingQueue
    LinkedBlockingDeque
    PriorityBlockingQueue
    SynchronousQueue

  6. threadFactory 线程工厂类

    可以为线程设置名称

  7. RejectedExecutionHandler

    当线程池数量大于maxPoolSize,并且阻塞队列也塞满了,此时会执行拒绝策略来处理请求。

运行逻辑:

  • 当线程池的数量小于corePoolSize时,来一个任务则创建一个线程
  • 当线程池的数量大于corePoolSize,且阻塞队列未满,则来一个任务放入阻塞队列
  • 当线程池数量大于corePoolSize且阻塞队列已满且小于maxPoolSize时,则来一个任务则创建一个新线程执行任务
  • 当线程池线程数量大于maxPoolSize,则执行拒绝策略拒绝新任务。
  • 当线程池数量超过corePoolSize,某个线程空闲时间超过keepAliveTime时,则线程终止,直到线程池的数量小于corePoolSize

拒绝策略

  1. AbortPolicy:抛出异常(默认)
  2. DiscardPolicy:抛弃任务
  3. DiscardOldestPolicy:丢弃最老的任务
  4. CallerRunsPolicy:将任务分配给当前执行execute方法的线程执行

线程池种类


  1. FixThreadPool
    固定大小的线程池
  2. CacheThreadPool
    缓存线程池
  3. SingleThreadExector
    单线程线程池
  4. ScheduledThreadPool
    调度线程池

CacheThreadPool和ScheduledThreadPool的最大线程数为Integer.MAX_VALUE,如果线程无限创建,会报OOM
FixThreadPool和SingleThreadExector的阻塞队列为LinkedBlockingQueue,最大长度也为Integer.MAX_VALUE,如果不断的给任务,也会报OOM异常


ThreadPoolExecutor示例代码:
    public static void main(String[] args) {
        int corePoolSize = 300;
        int maxPoolSize = 500;
        long aliveTime  = 10;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(500);
        MyThreadFactory threadFactory = new MyThreadFactory();
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, aliveTime, timeUnit, blockingQueue, threadFactory);
        for (int i = 900; i > 0; i--) {
            threadPool.submit(()->{
                System.out.println(Thread.currentThread().getName());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        // 不要忘了调用shutdown方法
        threadPool.shutdown();
    }


    static class MyThreadFactory implements ThreadFactory{
        private final AtomicInteger threadInteger = new AtomicInteger(0);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r,"MyThread-"+threadInteger.incrementAndGet());
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值