Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  •  普罗旺斯
  • 负责帅就完事了
  • 写了1,495,102字

该文章投稿至Nemo社区   Linux  板块 复制链接


获取CPU占用的工具

发布于 2016/07/18 10:12 1,212浏览 0回复 1,031

####这是之前在TCP SERVER里面使用到的一个工具,康云同志帮忙搜索到的,测试中,在Windows和Linux下都有效,这里也顺便记录下来:


package com.nemo.utils;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
import java.math.BigDecimal;

/**
* 获取操作系统信息的工具
* @author nemo
*
*/
public class SystemInfoUtils {

/**
* 获取CPU占用率
* @return
*/
public static String getCpuRatio() {
OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
int returnVal = -1;
try
{
Class clazz = operatingSystemMXBean.getClass();
Method method = clazz.getMethod("getSystemCpuLoad");
method.setAccessible(true);
Object objVal = method.invoke(operatingSystemMXBean);
if (objVal != null)
{
double doubleVal = Double.parseDouble(objVal.toString()) * 100; // 百分比运算
returnVal = new BigDecimal(doubleVal).setScale(0, BigDecimal.ROUND_HALF_UP).intValue(); // 四舍五入运算
}
} catch (Exception e)
{
e.printStackTrace();
return -1+"";
}
return returnVal+"";
}
}

点赞(0)
点了个评