Java获取系统内存、CPU、磁盘等信息

2023-05-16

前言:代码从别处摘抄收集,留着以后需要的时候使用,已经亲自测试可用,支持各种操作系统(Windows、mac、linux)参考项目https://github.com/oshi/oshi。

1、添加依赖环境

<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>3.12.2</version>
    </dependency>
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>net.java.dev.jna</groupId>
    <artifactId>jna-platform</artifactId>
    <version>5.2.0</version>
</dependency>

2、示例代码

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import com.sun.management.OperatingSystemMXBean;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;

/**
 * 系统监控
 */
public class SystemMonitor {

    public void init() {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {

                SystemInfo systemInfo = new SystemInfo();

                OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
                MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
                // 椎内存使用情况
                MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();

                // 初始的总内存
                long initTotalMemorySize = memoryUsage.getInit();
                // 最大可用内存
                long maxMemorySize = memoryUsage.getMax();
                // 已使用的内存
                long usedMemorySize = memoryUsage.getUsed();

                // 操作系统
                String osName = System.getProperty("os.name");
                // 总的物理内存
                String totalMemorySize = new DecimalFormat("#.##")
                        .format(osmxb.getTotalPhysicalMemorySize() / 1024.0 / 1024 / 1024) + "G";
                // 剩余的物理内存
                String freePhysicalMemorySize = new DecimalFormat("#.##")
                        .format(osmxb.getFreePhysicalMemorySize() / 1024.0 / 1024 / 1024) + "G";
                // 已使用的物理内存
                String usedMemory = new DecimalFormat("#.##").format(
                        (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / 1024.0 / 1024 / 1024)
                        + "G";
                // 获得线程总数
                ThreadGroup parentThread;
                for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
                        .getParent() != null; parentThread = parentThread.getParent()) {

                }

                int totalThread = parentThread.activeCount();

                // 磁盘使用情况
                File[] files = File.listRoots();
                for (File file : files) {
                    String total = new DecimalFormat("#.#").format(file.getTotalSpace() * 1.0 / 1024 / 1024 / 1024)
                            + "G";
                    String free = new DecimalFormat("#.#").format(file.getFreeSpace() * 1.0 / 1024 / 1024 / 1024) + "G";
                    String un = new DecimalFormat("#.#").format(file.getUsableSpace() * 1.0 / 1024 / 1024 / 1024) + "G";
                    String path = file.getPath();
                    System.err.println(path + "总:" + total + ",可用空间:" + un + ",空闲空间:" + free);
                    System.err.println("=============================================");
                }

                System.err.println("操作系统:" + osName);
                System.err.println("程序启动时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new Date(ManagementFactory.getRuntimeMXBean().getStartTime())));
                System.err.println("pid:" + System.getProperty("PID"));
                System.err.println("cpu核数:" + Runtime.getRuntime().availableProcessors());
                printlnCpuInfo(systemInfo);
                System.err.println("JAVA_HOME:" + System.getProperty("java.home"));
                System.err.println("JAVA_VERSION:" + System.getProperty("java.version"));
                System.err.println("USER_HOME:" + System.getProperty("user.home"));
                System.err.println("USER_NAME:" + System.getProperty("user.name"));
                System.err.println("初始的总内存(JVM):"
                        + new DecimalFormat("#.#").format(initTotalMemorySize * 1.0 / 1024 / 1024) + "M");
                System.err.println(
                        "最大可用内存(JVM):" + new DecimalFormat("#.#").format(maxMemorySize * 1.0 / 1024 / 1024) + "M");
                System.err.println(
                        "已使用的内存(JVM):" + new DecimalFormat("#.#").format(usedMemorySize * 1.0 / 1024 / 1024) + "M");
                System.err.println("总的物理内存:" + totalMemorySize);
                System.err
                        .println("总的物理内存:"
                                + new DecimalFormat("#.##").format(
                                        systemInfo.getHardware().getMemory().getTotal() * 1.0 / 1024 / 1024 / 1024)
                                + "M");
                System.err.println("剩余的物理内存:" + freePhysicalMemorySize);
                System.err
                        .println("剩余的物理内存:"
                                + new DecimalFormat("#.##").format(
                                        systemInfo.getHardware().getMemory().getAvailable() * 1.0 / 1024 / 1024 / 1024)
                                + "M");
                System.err.println("已使用的物理内存:" + usedMemory);
                System.err.println("已使用的物理内存:"
                        + new DecimalFormat("#.##").format((systemInfo.getHardware().getMemory().getTotal()
                                - systemInfo.getHardware().getMemory().getAvailable()) * 1.0 / 1024 / 1024 / 1024)
                        + "M");
                System.err.println("总线程数:" + totalThread);
                System.err.println("===========================");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 0, 60, TimeUnit.SECONDS);
    }

    /**
     * 打印 CPU 信息
     *
     * @param systemInfo
     */
    private void printlnCpuInfo(SystemInfo systemInfo) throws InterruptedException {
        CentralProcessor processor = systemInfo.getHardware().getProcessor();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        // 睡眠1s
        TimeUnit.SECONDS.sleep(1);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[CentralProcessor.TickType.NICE.getIndex()]
                - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
        long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()]
                - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
        long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()]
                - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
        long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()]
                - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
        long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()]
                - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
        long user = ticks[CentralProcessor.TickType.USER.getIndex()]
                - prevTicks[CentralProcessor.TickType.USER.getIndex()];
        long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()]
                - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
        long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()]
                - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        System.err.println("cpu核数:" + processor.getLogicalProcessorCount());
        System.err.println("cpu系统使用率:" + new DecimalFormat("#.##%").format(cSys * 1.0 / totalCpu));
        System.err.println("cpu用户使用率:" + new DecimalFormat("#.##%").format(user * 1.0 / totalCpu));
        System.err.println("cpu当前等待率:" + new DecimalFormat("#.##%").format(iowait * 1.0 / totalCpu));
        System.err.println("cpu当前空闲率:" + new DecimalFormat("#.##%").format(idle * 1.0 / totalCpu));
        System.err.format("CPU load: %.1f%% (counting ticks)%n", processor.getSystemCpuLoadBetweenTicks() * 100);
        System.err.format("CPU load: %.1f%% (OS MXBean)%n", processor.getSystemCpuLoad() * 100);
    }
}

转载自:https://www.cnblogs.com/rvs-2016/p/11169894.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java获取系统内存、CPU、磁盘等信息 的相关文章

  • ccf 游戏

    试题编号 xff1a 201604 4试题名称 xff1a 游戏时间限制 xff1a 1 0s内存限制 xff1a 256 0MB问题描述 xff1a 问题描述 小明在玩一个电脑游戏 xff0c 游戏在一个 n m的方格图上进行 xff0c
  • POJ 1738

    There is an old stone game At the beginning of the game the player picks n 1 lt 61 n lt 61 50000 piles of stones in a li
  • 电池充电电路(TP4059)详解

    电池充电电路 xff08 TP4059 xff09 详解 TP4059是一款完整的单节锂离子电池充电器 xff0c 带电池正负极反接保护反接功能 xff0c 支持高达600mA的充电电流 xff0c 更稳定的电流一致性 该芯片的充电电流可以
  • 洛谷刷题记录【入门1】顺序结构

    入门1 顺序结构 题单 洛谷 https www luogu com cn training 100 problems 1 A 43 B Problem 洛谷 输入两个整数 a b xff0c 输出它们的和 xff08 a b 10 xff
  • 安装CLOVER引导器到硬盘EFI分区

    彻底脱离CLOVER引导U盘 目录 xff1a 1使用EFI TOOLS Clover 安装CLOVER引导器到EFI分区 2使用Clover v2 3k rXXXX pkg 安装CLOVER引导器到EFI分区 前言 我们的电脑里已经安装好
  • 安装配置IIS+MySQL+PHP环境的详细教程(之篇二PHP安装)

    上一篇参考安装配置IIS 43 MySQL 43 PHP环境的详细教程之篇一IIS安装 安装配置IIS 43 MySQL 43 PHP环境的详细教程 xff08 之篇二PHP安装 xff09 在Windows 云服务器中进行 PHP 配置
  • sublime text 4 license

    sublime text 4 注册license 亲测可用 BEGIN LICENSE Mifeng User Single User License EA7E span class token operator span span cla
  • 1.3 生成器 Builder

    专业描述 生成器模式是一种创建型设计模式 xff0c 使你能够分步骤创建复杂对象 该模式允许你使用相同的创建代码生成不同类型和形式的对象 生成器模式结构 生成器 xff08 Builder xff09 接口声明在所有类型生成器中通用的产品构
  • 全网最全Flutter的学习文档,不可转载

    title Flutter全网最全学习笔记 xff01 Flutter学习文档 Author xff1a Brath 欢迎来到 brath 的 CSDN 博客 xff0c 你也可访问 brath top 到我的个人博客来进行观看 演示dem
  • idea启动SpringBoot程序后,出现Process finished with exit code 0并不能成功运行

    前言 最近在学习SpringBoot xff0c 把视屏看了一遍 xff0c 就心血来潮想先测试下 xff1b 然后在IDEA中新建SpringBoot项目 xff08 maven xff09 xff0c 然后就写个标准的hello Spr
  • mysql 定时删除过期数据记录

    首先连接mysql数据库 xff1a 1 查看MySQL事件功能开启 show variables like span class token string 39 sc 39 span span class token punctuatio
  • springboot多数据源使用canal同步master数据库

    canal数据库同步 canal源码 xff08 需要根据自己配置修改参数 xff09 准备 0 xff1a binlog文件 0 1 xff1a binlog文件包含两种类型 xff1a 索引文件 xff08 文件名后缀为 index x
  • nginx映射域名以及加证书https(SSL证书)

    1 映射一个域名到服务器80端口 2 在服务器nginx配置这个域名并重启 nginx conf默认配置 user root span class token punctuation span worker processes auto s
  • 严重 [RMI TCP Connection(3)-127.0.0.1]

    遇到这个问题网上搜了半天发现还是没解决 xff0c 最后发现是maven库的问题 1 这个问题一般是maven库的原因 xff0c 自己下载配置Repository仓库 xff0c 也可以使用IDEA自动下载一个库 下面我是使用IDEA下载
  • MySQL数据库删除数据(有外键约束)

    在MySQL中删除一张表或一条数据的时候 xff0c 出现有外键约束的问题 xff0c 于是就去查了下方法 xff1a span class hljs operator span class hljs keyword SELECT span
  • IDEA 第一次配置Tomcat找不到Tomcat server

    新装的一个电脑 xff0c 配置tomcat时候找不到tomcat server xff0c 这次做个记录 关闭项目 gt setting gt plugins gt 搜索tomcat安装 再次打开就可以看到了 如果还没有就应该是下面的情况
  • java.lang.NumberFormatException: null原因

    今天跑从公司SVN download下来的项目 xff0c 老实报java lang NumberFormatException null这个错 xff0c 页面还提示我系统异常 xff0c 从网上百度看的很多解决方案说是下面这些情况 xf
  • linux内核睡眠状态解析(转载)

    1 系统睡眠状态 睡眠状态是整个系统的全局低功耗状态 xff0c 在这种状态下 xff0c 用户空间的代码不能被执行并且整个系统的活动明显被降低 1 1 被支持的睡眠状态 取决于所运行平台的能力和配置选项 xff0c Linux内核能支持四
  • 记一次Debian11安装

    出现问题 安装成功之后无法启动 从官网上下载镜像之后 xff08 有网络镜像和完整镜像 xff09 xff0c 就是一步步下一步 xff0c 当时提醒我缺少固件 xff0c 我也没有注意 xff0c 以为会联网自动安装 xff0c 当时选择
  • 再谈 UITableView 的 estimatedRowHeight(转)好文章

    转载自 xff1a https kangzubin com uitableview estimatedrowheight 今天发现之前写的一个基于 UITableView 的列表页面存在如下问题 xff1a 当列表在滑动过程中 xff0c

随机推荐