线程池原理Executors

java线程池提供的几种常用的线程创建方法

  • newFixedThreadPool
  • newSingleThreadExecutor
  • newCachedThreadPool
  • newScheduledThreadPool

阿里巴巴开发规约

在这里插入图片描述

线程池原理

  • jdk和阿里规约 好像有点小矛盾,那么就需要深入了解下底层实现,才可以知其所以然
  • 先来看下java多线程的几种创建方法(点开源码看)
    在这里插入图片描述在这里插入图片描述在这里插入图片描述
  • 发现java提供的几种创建线程池的方法源码中都是通过 new ThreadPoolExecutor 进行实现的
  • 那么就来深入了解以下ThreadPoolExecutor的构造函数
/**
     * 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) {
        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;
    }
  • 主要讲解构造函数参数,上面源码中也有解释,这里通过中文再次进行深入理解一下

    • 【int corePoolSize 】核心线程数
    • 【int maximumPoolSize】最大线程数
    • 【long keepAliveTime】空闲线程在等待新任务复用这个线程,所等待的时间
    • 【TimeUnit unit】keepAliveTime时间的单位
    • 【BlockingQueue workQueue】创建的线程任务,大于核心线程数之后,大于的部分任务,放在队列中,默认值是Integer.MAX_VALUE 当创建的线程任务超级大时,队列就有可能出现OOM
    • 【ThreadFactory threadFactory】执行器时要使用的工厂创建新线程
    • 【RejectedExecutionHandler handler】当创建的线程任务> workQueue数量+最大线程数时,就会执行“拒绝执行策略”,注意:RejectedExecutionHandler是一个接口,常见的有几种“拒绝执行策略如下”
      • AbortPolicy 抛出一个RejectedExecutionException异常,并丢弃当前线程任务【默认值】
      • DiscardPolicy 忽略,什么也不做,直接丢弃
      • DiscardOldestPolicy 线程没有结束时,从缓存队列中抛弃最老的一条任务,最老的一条任务就是队列中的队头的数据,把当前线程任务放入缓存队列
      • RejectHandler 抛出一个RejectedExecutionException异常 和AbortPolicy基本一样,具体差异可以看下源码,感觉此处的差异点设置的没有意义,个人觉得可以删除这个“拒绝执行策略”
      • CallerRunsPolicy 线程没有结束时,用调用者的线程执行当前任务
      • 自定义“拒绝执行策略”,实现RejectedExecutionHandler接口,比如说,可以打印日志、MQ、数据库、redis等等,保证最终数据的一致性
  • 总结下执行过程
    当一个任务通过execute(Runnable)方法欲添加到线程池时:
    1 、如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
    2 、如果此时线程池中的数量等于 corePoolSize,但是缓冲队列 workQueue未满,那么任务被放入缓冲队列。
    3 、如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maximumPoolSize,建新的线程来处理被添加的任务。
    4、如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maximumPoolSize,那么通过 handler所指定的策略来处理此任务。也就是:处理任务的优先级为:核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize,如果三者都满了,使用handler处理被拒绝的任务。

  • 最后放入自己写的一个测试Demo

	public static void main(String[] args) {
        ExecutorService executorService = PlatformRestaurantApplication.newTreadPool();
        for (int i=0 ; i < 10; i++) {
            int finalI = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try{
                        Thread.sleep(900);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println(
                            new StringJoiner("-")
                                    .add(Thread.currentThread().getName())
                                    .add(String.valueOf(finalI))
                                    .toString());
                }
            });
        }

    }


    public static ExecutorService newTreadPool() {

        return new ThreadPoolExecutor(2, 5, 0L,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(2));
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值