搜索
查看
编辑修改
首页
UNITY
NODEJS
PYTHON
AI
GIT
PHP
GO
CEF3
JAVA
HTML
CSS
搜索
编程领航者
这个屌丝很懒,什么也没留下!
关注作者
热门标签
jquery
HTML
CSS
PHP
ASP
PYTHON
GO
AI
C
C++
C#
PHOTOSHOP
UNITY
iOS
android
vue
xml
爬虫
SEO
LINUX
WINDOWS
JAVA
MFC
CEF3
CAD
NODEJS
GIT
Pyppeteer
article
热门文章
1
搭建Redis集群
2
RocketMQ Dashboard 详解
3
QT Progress Bar 进度条_qt progressbar
4
linux下的umask()函数,Linux----centos下的umask详解(翻译)
5
国密算法 SM2 公钥加密 非对称加密 数字签名 密钥协商 python实现完整代码_python sm2加密
6
卡耐基人际关系学5
7
效率交响曲:AIOps 协调卓越运营
8
Python之pdf内容读取_python读取pdf内容
9
SpringBoot 学习笔记(3) -- [spring Boot集成阿里Druid数据源,整合Mybatis搭建一个案例试试]_spring4集成阿里数据源
10
idea 创建 spring boot
当前位置:
article
> 正文
java获取计算机cpu利用率和内存使用信息
作者:编程领航者 | 2024-02-04 13:52:21
赞
踩
java 计算目标cpu利用率
利用java获取计算机cpu利用率和内存使用信息
1.pojo类:
public class MonitorInfoBean {
/** 可使用内存. */
private long totalMemory;
/** 剩余内存. */
private long freeMemory;
/** 最大可使用内存. */
private long maxMemory;
/** 操作系统. */
private String osName;
/** 总的物理内存. */
private long totalMemorySize;
/** 剩余的物理内存. */
private long freePhysicalMemorySize;
/** 已使用的物理内存. */
private long usedMemory;
/** 线程总数. */
private int totalThread;
/** cpu使用率. */
private double cpuRatio;
public long getFreeMemory() {
return freeMemory;
}
public void setFreeMemory(long freeMemory) {
this.freeMemory = freeMemory;
}
public long getFreePhysicalMemorySize() {
return freePhysicalMemorySize;
}
public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
this.freePhysicalMemorySize = freePhysicalMemorySize;
}
public long getMaxMemory() {
return maxMemory;
}
public void setMaxMemory(long maxMemory) {
this.maxMemory = maxMemory;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public long getTotalMemory() {
return totalMemory;
}
public void setTotalMemory(long totalMemory) {
this.totalMemory = totalMemory;
}
public long getTotalMemorySize() {
return totalMemorySize;
}
public void setTotalMemorySize(long totalMemorySize) {
this.totalMemorySize = totalMemorySize;
}
public int getTotalThread() {
return totalThread;
}
public void setTotalThread(int totalThread) {
this.totalThread = totalThread;
}
public long getUsedMemory() {
return usedMemory;
}
public void setUsedMemory(long usedMemory) {
this.usedMemory = usedMemory;
}
public double getCpuRatio() {
return cpuRatio;
}
public void setCpuRatio(double cpuRatio) {
this.cpuRatio = cpuRatio;
}
}
2. 实现类:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.StringTokenizer;
import sun.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
public class cpu {
private static final int CPUTIME = 30;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
private static final File versionFile = new File("/proc/version");
private static String linuxVersion = null;
public double getCpuRatio(){
// 操作系统
String osName = System.getProperty("os.name");
double cpuRatio = 0;
if (osName.toLowerCase().startsWith("windows")) {
return cpuRatio = this.getCpuRatioForWindows();
}
else {
return cpuRatio = this.getCpuRateForLinux();
}
}
/**
* 获得当前的监控对象.
* @return 返回构造好的监控对象
*/
public MonitorInfoBean getMonitorInfoBean() throws Exception {
int kb = 1024;
// 可使用内存
long totalMemory = Runtime.getRuntime().totalMemory() / kb;
// 剩余内存
long freeMemory = Runtime.getRuntime().freeMemory() / kb;
// 最大可使用内存
long maxMemory = Runtime.getRuntime().maxMemory() / kb;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 操作系统
String osName = System.getProperty("os.name");
// 总的物理内存
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
// 剩余的物理内存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
// 已使用的物理内存
long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
.getFreePhysicalMemorySize())
/ kb;
// 获得线程总数
ThreadGroup parentThread;
for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
.getParent() != null; parentThread = parentThread.getParent())
;
int totalThread = parentThread.activeCount();
double cpuRatio = 0;
if (osName.toLowerCase().startsWith("windows")) {
cpuRatio = this.getCpuRatioForWindows();
}
else {
cpuRatio = this.getCpuRateForLinux();
}
// 构造返回对象
MonitorInfoBean infoBean = new MonitorInfoBean();
infoBean.setFreeMemory(freeMemory);
infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
infoBean.setMaxMemory(maxMemory);
infoBean.setOsName(osName);
infoBean.setTotalMemory(totalMemory);
infoBean.setTotalMemorySize(totalMemorySize);
infoBean.setTotalThread(totalThread);
infoBean.setUsedMemory(usedMemory);
infoBean.setCpuRatio(cpuRatio);
return infoBean;
}
private static double getCpuRateForLinux(){
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
StringTokenizer tokenStat = null;
try{
System.out.println("Get usage rate of CUP , linux version: "+linuxVersion);
Process process = Runtime.getRuntime().exec("top -b -n 1");
is = process.getInputStream();
isr = new InputStreamReader(is);
brStat = new BufferedReader(isr);
if(linuxVersion.equals("2.4")){
brStat.readLine();
brStat.readLine();
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
String user = tokenStat.nextToken();
tokenStat.nextToken();
String system = tokenStat.nextToken();
tokenStat.nextToken();
String nice = tokenStat.nextToken();
System.out.println(user+" , "+system+" , "+nice);
user = user.substring(0,user.indexOf("%"));
system = system.substring(0,system.indexOf("%"));
nice = nice.substring(0,nice.indexOf("%"));
float userUsage = new Float(user).floatValue();
float systemUsage = new Float(system).floatValue();
float niceUsage = new Float(nice).floatValue();
return (userUsage+systemUsage+niceUsage)/100;
}else{
brStat.readLine();
brStat.readLine();
tokenStat = new StringTokenizer(brStat.readLine());
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
tokenStat.nextToken();
String cpuUsage = tokenStat.nextToken();
System.out.println("CPU idle : "+cpuUsage);
Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf("%")));
return (1-usage.floatValue()/100);
}
} catch(IOException ioe){
System.out.println(ioe.getMessage());
freeResource(is, isr, brStat);
return 1;
} finally{
freeResource(is, isr, brStat);
}
}
private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br){
try{
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
/**
* 获得CPU使用率.
* @return 返回cpu使用率
*/
private double getCpuRatioForWindows() {
try {
String procCmd = System.getenv("windir")
+ "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
+ "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
// 取进程信息
long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
Thread.sleep(CPUTIME);
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
if (c0 != null && c1 != null) {
long idletime = c1[0] - c0[0];
long busytime = c1[1] - c0[1];
return Double.valueOf(
PERCENT * (busytime) / (busytime + idletime))
.doubleValue();
} else {
return 0.0;
}
} catch (Exception ex) {
ex.printStackTrace();
return 0.0;
}
}
/**
* 读取CPU信息.
* @param proc
*/
private long[] readCpu(final Process proc) {
long[] retn = new long[2];
try {
proc.getOutputStream().close();
InputStreamReader ir = new InputStreamReader(proc.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line = input.readLine();
if (line == null || line.length() < FAULTLENGTH) {
return null;
}
int capidx = line.indexOf("Caption");
int cmdidx = line.indexOf("CommandLine");
int rocidx = line.indexOf("ReadOperationCount");
int umtidx = line.indexOf("UserModeTime");
int kmtidx = line.indexOf("KernelModeTime");
int wocidx = line.indexOf("WriteOperationCount");
long idletime = 0;
long kneltime = 0;
long usertime = 0;
while ((line = input.readLine()) != null) {
if (line.length() < wocidx) {
continue;
}
// 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
// ThreadCount,UserModeTime,WriteOperation
String caption = Bytes.substring(line, capidx, cmdidx - 1)
.trim();
String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") >= 0) {
continue;
}
// log.info("line="+line);
if (caption.equals("System Idle Process")
|| caption.equals("System")) {
idletime += Long.valueOf(
Bytes.substring(line, kmtidx, rocidx - 1).trim())
.longValue();
idletime += Long.valueOf(
Bytes.substring(line, umtidx, wocidx - 1).trim())
.longValue();
continue;
}
kneltime += Long.valueOf(
Bytes.substring(line, kmtidx, rocidx - 1).trim())
.longValue();
usertime += Long.valueOf(
Bytes.substring(line, umtidx, wocidx - 1).trim())
.longValue();
}
retn[0] = idletime;
retn[1] = kneltime + usertime;
return retn;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
proc.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/** 测试方法.
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
cpu c =new cpu();
System.out.println("cpu占有率1=" + c.getCpuRatio());
System.out.println("cpu占有率2=" + c.getCpuRatioForWindows());
MonitorInfoBean monitorInfo = c.getMonitorInfoBean();
System.out.println("cpu占有率=" + monitorInfo.getCpuRatio());
System.out.println("可使用内存=" + monitorInfo.getTotalMemory());
System.out.println("剩余内存=" + monitorInfo.getFreeMemory());
System.out.println("最大可使用内存=" + monitorInfo.getMaxMemory());
System.out.println("操作系统=" + monitorInfo.getOsName());
System.out.println("总的物理内存=" + monitorInfo.getTotalMemorySize() + "kb");
System.out.println("剩余的物理内存=" + monitorInfo.getFreeMemory() + "kb");
System.out.println("已使用的物理内存=" + monitorInfo.getUsedMemory() + "kb");
System.out.println("线程总数=" + monitorInfo.getTotalThread() + "kb");
}
}
class Bytes {
public static String substring(String src, int start_idx, int end_idx){
byte[] b = src.getBytes();
String tgt = "";
for(int i=start_idx; i<=end_idx; i++){
tgt +=(char)b[i];
}
return tgt;
}
}
该文章转自:
[url]http://blog.csdn.net/farreaching665/article/details/7098839[/url]
声明:
本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:
https://www.wpsshop.cn/article/detail/58872
推荐阅读
article
Java+
SSM
+MySQL基于微信的在线协同办公小程序(附源码 调试 文档)_可以用ssm框架开发...
SSM
框架是Spring、SpringMVC和MyBatis的集合,它简化了企业级应用的开发,提高了开发效率。通过微信平...
赞
踩
article
接口
自动化测试
框架(Java 实现)_java接口
自动化测试
框架...
通过 yaml 配置接口操作和用例_java接口
自动化测试
框架java接口
自动化测试
框架 ...
赞
踩
article
[
云计算
| AWS 实践 ] Java 如何重命名 Amazon S3 中的文件和文件夹_jav...
在本博文中,我们将探讨 如何使用 Java 重命名 Amazon S3 存储桶中的对象(文件或文件夹)。Amazon S...
赞
踩
article
Java 新手如何使用Spring MVC 中的查询字符串和查询参数...
Java 新手如何使用Spring MVC 中的查询字符串和查询参数Java 新手如何使用Spring MVC 中的查询...
赞
踩
article
全网最全的 Java 技术栈内容梳理(持续更新中)_java技术栈...
大家好,我是栗筝i,从 2022 年 10 月份开始,我将全面梳理 Java 技术栈的相关内容,一方面是对自己学习内容进...
赞
踩
article
【
数据库
课设】机票预订系统
java
+my
sql
实现 附源码_基于my
sql
,设计并实现一个简单的旅...
数据库
的课程设计,题目 [ 机票预订系统 ] ,(
java
sql
代码 系统说明书)的下载地址放在末尾。_基于my
sql
...
赞
踩
article
学生信息管理系统(JAVA+MYSQL)...
基于Java swing+MySQL实现学生信息管理系统:功能:1录入学生基本信息的功能; 2查询学生基本信息的功能; ...
赞
踩
article
猿创征文|弃文从工,从小白到蚂蚁工程师,我的 Java 成长之路_弃文就工...
最近 CSDN 开展了猿创征文,希望博主写文章讲述自己在某个领域的技术成长历程。之前也曾想找个机会写篇文章,记录下自己的...
赞
踩
article
华为
机试
(
J
A
V
A
)
真题
Od【
A
卷+B卷+C卷+D卷】_
华为
od
机试
真题
...
2022.11 开始
华为
机试
Od 应该加新题了,优先更新最新的题目。_
华为
od
机试
真题
华为
od
机试
真题
...
赞
踩
article
华为
O
D
机考
机试
真题
目录(C卷 +
D
卷 + B卷 + A卷) + 考点说明(C++
Java
J...
O
D
,全称(Outsourcing
D
ispacth)模式,目前
华为
和德科联合招聘的简称。
华为
社招基本都是
O
D
招聘,17...
赞
踩
article
[附源码]
JAVA
+
ssm
基于
的
餐厅
管理系统
(程序+Lw)_
数据库
餐厅
管理系统
...
项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+...
赞
踩
article
基于
SpringBoot
+Vue+Mysql+Java
高校
校园
点餐
系统
(附源码)_
校园
点餐
系统
:点...
【毕业设计】基于
SpringBoot
+Vue
高校
校园
点餐
系统
_
校园
点餐
系统
:
点餐
、
食堂
管理
、
商户
管理
和菜品
管理
(
java
...
赞
踩
article
数据库
课程
大作业:
课程
管理系统
——
java
实现
、图形化,我写了My
SQL
和
SQL
两个版本_
数据库
课设...
演示视频项目源码、文档、
数据库
脚本下载地址:https://github.com/Chaim16/CurseManage...
赞
踩
article
[独有源码]
java
-jsp
校园卡
食堂
前端
管理系统
的
设计
与
实现
92515从不会做毕业
设计
到成功完成
的
...
选题背景:随着社会
的
发展和科技
的
进步,
校园卡
食堂
前端
管理系统
逐渐成为高校
食堂
管理
的
重要组成部分。传统
的
人工管理方式存在诸...
赞
踩
article
数据库
--
教务
管理系统
(
数据库
部分
--
Java
-
jdbc
连接)_
教务
管理系统
数据库
...
我所设计的
教务
管理系统
包括6大部分,学生信息、教师信息、课程信息、班级信息、选课信息、教授信息。该系统可以通过不同的群体...
赞
踩
article
java
se 计算机专业技能-
Java
专项练习(选择题)(一)_1
public
class
...
java
se 计算机专业技能-
Java
专项练习(选择题):1.类ABC定义如下:1.
public
class
ABC{...
赞
踩
article
Java
:
面试题...
1. 什么是
Java
虚拟机?为什么
Java
被称作是“平台无关的编程语言”?答
:
Java
虚拟机是一个可以执行
Java
字节码...
赞
踩
article
2085.
统计
出现
过
一次
的
公共
字符串
(
Java
)...
给你两个
字符串
数组 words1 和 words2 ,请你返回在两个
字符串
数组中 都恰好
出现
一次
的
字符串
的
数目。208...
赞
踩
article
Java
:双
缓冲
队列...
双
缓冲
队列就是冲着同步/互斥的开销来的。我们知道,在多个线程并发访问同一个资源的时候,需要特别注意线程的同步问题。稍稍不...
赞
踩
article
HDFS
Java
API
操作(
IDEA
版)...
目标编写
Java
API
来操作
HDFS
,完成的操作有:文件上传、文件下载、新建文件夹、查看文件、删除文件。前提条件1.W...
赞
踩
相关标签
java
mysql
SSM
微信小程序
课程设计
测试用例
单元测试
软件测试
自动化测试
测试工程师
云计算
aws
云平台
spring
mvc
Java技术栈
开发语言
程序人生
学习方法
1024程序员节
jar
sql
数据库