java线程池中的核心参数

2023-05-16

线程池中的核心参数
int corePoolSize:核心线程数,即使线程池中无任务执行,也会创建该数量的线程。
int maximumPoolSize:最大线程数,当核心线程数不够,且队列已满的情况下,会另外创建线程执行任务。
long keepAliveTime:当线程池中的线程处于空闲状态,超过KeepAliveTime时间,则销毁该线程,保持运行的线程数=核心线程数。
BlockingQueue workQueue:任务队列,当任务大于核心线程数,任务会加到队列中等待执行
RejectedExecutionHandler defaultHandler:拒绝策略,详情参考
线程池中四种拒绝策略

下面是线程池的使用以及验证参数
设置核心线程数2,最大线程数7,空闲时存活时间8秒,队列容量3,设置10个线程任务,放入线程池中,为了造成线程数堆积,让任务睡眠5秒。当核心线程数有任务执行,则将新任务加入队列,当任务队列满了,则扩大线程至最大线程数。

public class ThreadPool {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(3);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor
                (2, 7, 8, TimeUnit.SECONDS, blockingQueue, new ThreadPoolExecutor.DiscardPolicy());
        for(int i = 0; i < 10; i++) {
            threadPoolExecutor.execute(
                    new Thread(){
                        @Override
                        public void run() {
                            try{
                                System.out.println(Thread.currentThread().getName()+" start");
                                //体现线程数满的场景,让任务在此处停留,造成线程堆积
                                Thread.sleep(5000);
                                System.out.println(Thread.currentThread().getName() + " end");
                            }catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
            );
        }
        //验证KeepAlive,当空闲线程超过KeepAliveTime=8秒,则将线程数降低至核心线程
        Thread.sleep(30000);
        System.out.println("休息了30s...");
        for(int i = 0; i < 5; i++) {
            threadPoolExecutor.execute(
                    new Thread(){
                        @Override
                        public void run() {
                            try{
                                System.out.println(Thread.currentThread().getName()+" start");
                                Thread.sleep(3000);
                                System.out.println(Thread.currentThread().getName() + " end");
                            }catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
            );
        }
    }
}

执行结果,可以发现起了7个线程执行任务,因为堆积的任务数超过核心数+队列容量,则扩大至最大线程数7。中间休息的30秒,为了验证空闲时线程数是否会降低至核心线程数,观察运行结果,可以发现保留了两个线程数执行任务。

pool-1-thread-1 start
pool-1-thread-2 start
pool-1-thread-3 start
pool-1-thread-4 start
pool-1-thread-5 start
pool-1-thread-6 start
pool-1-thread-7 start
pool-1-thread-2 end
pool-1-thread-3 end
pool-1-thread-2 start
pool-1-thread-1 end
pool-1-thread-3 start
pool-1-thread-1 start
pool-1-thread-6 end
pool-1-thread-4 end
pool-1-thread-7 end
pool-1-thread-5 end
pool-1-thread-2 end
pool-1-thread-1 end
pool-1-thread-3 end
休息了30s...
pool-1-thread-3 start
pool-1-thread-1 start
pool-1-thread-1 end
pool-1-thread-1 start
pool-1-thread-3 end
pool-1-thread-3 start
pool-1-thread-3 end
pool-1-thread-3 start
pool-1-thread-1 end
pool-1-thread-3 end

部分源码:

public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        //运行的线程数小于核心线程数,则加入任务线程,
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        //如果加入队列成功,进行两次检查能否加入
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        //执行到此处,说明核心线程数和队列都满了,则需创建新线程执行,
        //如果创建新线程失败,则执行拒绝策略
        else if (!addWorker(command, false))
            reject(command);
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java线程池中的核心参数 的相关文章

  • CentOS 7下安装MPICH3.2过程详解

    最近由于专业需要 xff0c 需要在CentOS 7平台下安装并行计算包MPICH 由于我才接触Linux xff0c 鸟哥的基础入门书也才看了四分之一不到 xff0c 所以安装也一步一步按照官方给的文档安装 官方安装方法 首先附上官网给出
  • 洛谷 P3366 【模板】最小生成树

    洛谷 P3366 模板 最小生成树 题目 给出一个无向图 xff0c 求出最小生成树 xff0c 如果该图不连通 xff0c 则输出orz 题目链接 模板 最小生成树 洛谷 输入 第一行包含两个整数N M xff0c 表示该图共有N个结点和
  • 2019 计蒜之道 复赛 D “星云系统”

    2019 计蒜之道 复赛 D 星云系统 题目 现在给定你一个字符串s以及一个整数k xff0c 请求出s的字典序最小的长度为k的子序列 题目链接https nanti jisuanke com t 39614 输入格式 第一行一个由小写英文
  • Linux mysql 配置

    一 数据库处室化密码 刚刚装好的数据库需要重置密码 alter user user identified by 39 12345678 39 如果是测试环境 或者自己玩的环境 设置密码过于简单 可以通过一下命令修改关于密码的校验 set g
  • 二进制安装Kubernetes(k8s) v1.26.0 IPv4/IPv6双栈

    二进制安装Kubernetes xff08 k8s xff09 v1 26 0 IPv4 IPv6双栈 https github com cby chen Kubernetes 开源不易 xff0c 帮忙点个star xff0c 谢谢了 介
  • ThinkPad E430 蓝牙驱动 BCM43142A0

    最近我意外发现公司的 ThinkPad E430 笔记本竟然是带有蓝牙的 D 查看蓝牙设备标识 ID 利用 lsusb 命令找到蓝牙模块信息 Bus 001 Device 004 ID 105b e065 Foxconn Internati
  • cephadm 安装部署 ceph 集群

    介绍 手册 xff1a https access redhat com documentation zh cn red hat ceph storage 5 html architecture guide index http docs c
  • PVE Cloud-INIT 模板配置

    PVE Cloud INIT 模板配置 Cloud init是什么 Cloud init是开源的云初始化程序 xff0c 能够对新创建弹性云服务器中指定的自定义信息 xff08 主机名 密钥和用户数据等 xff09 进行初始化配置 通过Cl
  • openstack 环境部署

    22 1 了解云计算 人类基于千年的物种衍变基础 xff0c 在这个世纪终于有了爆发式的科技成果 xff0c 尤其这二十年内互联网的发展 xff0c 更像是一种催化剂 xff0c 让原本已经热闹的地球更加的沸腾 xff0c 互联网经济泡沫破
  • C语言,计算圆的面积程序

    C语言 xff0c 计算圆的面积程序 span class token comment 计算圆的面积程序 日期 xff1a 2020 8 29 姓名 xff1a 张倩峰 span span class token macro propert
  • 博图软件搜索不到网卡

  • 台达伺服手动调试

  • 博途V15.1激活工具出错。

    博图V15 1激活 xff0c 软件出错 出现以下报错信息 解决方法 xff1a 下载新版本激活工具 再次激活
  • winCC正常运行,不显示画面。

    winCC正常运行 xff0c 不显示画面 解决方法 xff1a 需要重装系统 xff0c 重新安装博途
  • S7-1500PLC仿真

    S7 1500PLC仿真
  • 一些已安装产品需要许可证,请启动Automation License Manager

    更新系统版本号 完成更新 xff0c 再次安装即可解决该问题
  • ubuntu 硬盘管理工具

    就我目前所用的系统举例说明吧 xff0c 应该都大同小异的 有图形界面的 xff0c 也有命令行的 xff1a 首先是 ubuntu 系统自带的 Disk Utility 工具集 利用该工具可以对硬盘进行 Format Drive View
  • MCS-51单片机,定时1分钟,汇编程序

    MCS 51单片机 xff0c 定时1分钟 xff0c 汇编程序 去博客设置页面 xff0c 选择一款你喜欢的代码片高亮样式 xff0c 下面展示同样高亮的 代码片 span class token constant ORG span 00
  • c++枚举字符串转换工具

    为什么会需要这样一个枚举转字符串 xff0c 字符串转枚举的工具 xff1f 在太多的工程中 xff0c 我们可能都需要将一些枚举 整形标记打到日志中去 xff0c 如果只打印数组 xff0c 那也不行啊 xff0c 出问题翻看日志 xff
  • AD16在PCB布局的时候如何批量复制布局布线!!

    本人也是看了很多博主的帖子反反复复推敲 xff0c 最后发现有的博主没讲到关键部分所以在批量复制布局的时候总是事与愿违 话不多说请看招 xff01 第一步选中需要复制的布局 xff01 如图所示 第二步 复制选中布局的 offset Cha

随机推荐