Java 线程池

参数

下面是 ThreadPoolExecutor 其中一个构造方法,可以看到 ThreadPoolExecutor 一共有7个参数:

  • corePoolSize:核心线程数,默认创建出来后不会被回收,可以通过调用allowCoreThreadTimeOut(true)方法允许回收
  • maximumPoolSize:最大线程数
  • keepAliveTime:当线程数大于核心线程数时,多余的线程等待任务的时间,超过时间没有分配到任务被回收
  • unit:传入的 keepAliveTime 的单位
  • workQueue:工作队列,当核心线程数满了后,任务将加入此队列,队列满后判断是否达到最大线程数,如果没有,创建新的线程执行任务,否则执行拒绝策略
  • threadFactory:线程工厂
  • handler:拒绝策略,默认拒绝策略为 AbortPolicy(抛出RejectedExecutionException异常)

过程:先创建核心线程执行任务,核心线程满了后放到工作队列,队列满后判断是否达到最大线程数,如果没有,创建新的线程执行任务,否则执行拒绝策略
在这里插入图片描述

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

        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

拒绝策略

一共有四种拒绝策略:

  1. AbortPolicy,抛出 RejectedExecutionException 异常(默认的拒绝策略)
  2. DiscardPolicy,抛弃任务,下面源码中可以看到该策略的 rejectedExecution 方法为空方法
  3. DiscardOldestPolicy,丢弃最早的未处理的任务
  4. CallerRunsPolicy,由调用 execute 方法的线程直接执行该任务
    /**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
        public AbortPolicy() { }
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }


    /**
     * A handler for rejected tasks that silently discards the
     * rejected task.
     */
    public static class DiscardPolicy implements RejectedExecutionHandler {
        public DiscardPolicy() { }
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
    }


    /**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        public DiscardOldestPolicy() { }
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }


    /**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     */
    public static class CallerRunsPolicy implements RejectedExecutionHandler {
        public CallerRunsPolicy() { }
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
    }

线程池工具类 Executors 提供的部分线程池

  1. FixedThreadPool
  2. SingleThreadExecutor
  3. CachedThreadPool
  4. ScheduledThreadPool

FixedThreadPool

FixedThreadPool 将核心线程数和最大线程数都设为传入的 nThreads,工作队列使用 LinkedBlockingQueue,从LinkedBlockingQueue 构造方法可以看到,该队列最大长度为 Integer.MAX_VALUE,容易造成内存溢出
在这里插入图片描述


    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

SingleThreadExecutor

SingleThreadExecutor 将核心线程数和最大线程数都设为 1,工作队列也使用 LinkedBlockingQueue,容易造成内存溢出(该队列最大长度为 Integer.MAX_VALUE)

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

CachedThreadPool

CachedThreadPool 将核心线程数设为 0,最大线程数都设为 Integer.MAX_VALUE

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

ScheduledThreadPool

将最大线程数设为 Integer.MAX_VALUE

    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

Executors 提供的线程池要么最大线程数要么工作队列的长度为 Integer.MAX_VALUE,容易造成内存溢出,所以实际上基本都使用自定义的线程池。
自定义线程池根据业务类型设置线程数:
IO密集型设为 2*cpu核数
cpu密集型设为 cpu核数+1
混合业务可以拆分为IO型+cpu型
线程数这样设置只是大概参数,想要更精准需要通过测试获得一个比较合适的数量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值