高并发线程池(三、创建线程池)

不要通过Executors类来创建线程池,一定要通过new ThreadPoolExecutor(…)来创建线程池。(参照阿里JAVA开发规范1.5泰山版)

先来介绍创建线程池涉及到的7个参数。

    public ThreadPoolExecutor(int corePoolSize, //核心线程数
                              int maximumPoolSize, //最大线程数
                              long keepAliveTime, //保持时间
                              TimeUnit unit,  //保持时间类型
                              BlockingQueue<Runnable> workQueue,  //任务队列
                              ThreadFactory threadFactory,  //线程池工厂
                              RejectedExecutionHandler handler //拒绝策略)

我们一一来解释

核心线程数 和 最大线程数

线程池中的线程分为两种,一种为核心线程(Daemon),一种是普通线程。核心线程是我们线程池启动后最少要维护的线程(这里指的是一旦新增任务,核心线程全部启动后),当核心线程都在执行任务的时候,新的任务又来了,那么任务放入队列中,并且新增普通线程来处理。普通线程数最多为 MAX-CORE。

keepAliveTime 和 unit

当普通线程在keepAliveTime个时间单位unit后没有任务执行,那么线程池主动释放掉普通线程,归还给操作系统。

workQueue

任务队列
1.SynchronousQueue
队列长度为0,有新的任务必须消费否则阻塞。
2.ArrayBlockingQueue
有界队列
3.LinkedBlockingDeque
“无界队列” (Integer.MAX_VALUE)
等类型。

threadFactory

线程工厂,可以自定义,不指定的话默认defalut。(建议实际环境中自定义)

RejectedExecutionHandler

拒绝策略,一般用不上,时间环境需要自定义。

根据打印信息观察线程池内部任务队列和线程的信息。

        int MaxCPU =  Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(MaxCPU
                ,MaxCPU
                ,60
                ,TimeUnit.SECONDS
                , new LinkedBlockingQueue()

        );

        for(int i=0; i<3; i++){
            threadPoolExecutor.execute(() -> {
                try {
                    Thread.sleep(8000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(threadPoolExecutor.toString());


        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


java.util.concurrent.ThreadPoolExecutor@44e81672[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值