java 怎么查看服务器cpu使用率的CPU使用率

博客分类:
JXM:Monitoring and Management Interface for the Java(TM) Platform 通过jmx可以监控vm内存使用,系统内存使用等 以下是网上某博客代码,特点是通过window和linux命令获得CPU使用率。
利用java程序实现获取计算机cpu利用率和内存使用信息。
创建一个Bean用来存贮要得到的信
public class MonitorInfoBean {
/** 可使用内存. */
private long totalM
剩余内存. */
private long freeM
/** 最大可使用内存. */
private long maxM
/** 操作系统. */
private String osN
/** 总的物理内存. */
private long totalMemoryS
/** 剩余的物理内存. */
private long freePhysicalMemoryS
/** 已使用的物理内存. */
private long usedM
/** 线程总数. */
private int totalT
/** cpu使用率. */
private double cpuR
public long getFreeMemory() {
return freeM
public void setFreeMemory(long freeMemory) {
this.freeMemory = freeM
public long getFreePhysicalMemorySize() {
return freePhysicalMemoryS
public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
this.freePhysicalMemorySize = freePhysicalMemoryS
public long getMaxMemory() {
return maxM
public void setMaxMemory(long maxMemory) {
this.maxMemory = maxM
public String getOsName() {
return osN
public void setOsName(String osName) {
this.osName = osN
public long getTotalMemory() {
return totalM
public void setTotalMemory(long totalMemory) {
this.totalMemory = totalM
public long getTotalMemorySize() {
return totalMemoryS
public void setTotalMemorySize(long totalMemorySize) {
this.totalMemorySize = totalMemoryS
public int getTotalThread() {
return totalT
public void setTotalThread(int totalThread) {
this.totalThread = totalT
public long getUsedMemory() {
return usedM
public void setUsedMemory(long usedMemory) {
this.usedMemory = usedM
public double getCpuRatio() {
return cpuR
public void setCpuRatio(double cpuRatio) {
this.cpuRatio = cpuR
之后,建立bean的接口
public interface IMonitorService {
public MonitorInfoBean getMonitorInfoBean() throws E
然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。
import java.io.InputStreamR
import java.io.LineNumberR
import sun.management.ManagementF
import com.sun.management.OperatingSystemMXB
import java.io.*;
import java.util.StringT
* 获取系统信息的业务逻辑实现类.
* @author GuoHuang
public class MonitorServiceImpl implements IMonitorService {
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 =
* 获得当前的监控对象.
* @return 返回构造好的监控对象
* @throws Exception
* @author GuoHuang
public MonitorInfoBean getMonitorInfoBean() throws Exception {
int kb = 1024;
// 可使用内存
long totalMemory = Runtime.getRuntime().totalMemory() /
// 剩余内存
long freeMemory = Runtime.getRuntime().freeMemory() /
// 最大可使用内存
long maxMemory = Runtime.getRuntime().maxMemory() /
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean();
// 操作系统
String osName = System.getProperty("os.name");
// 总的物理内存
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() /
// 剩余的物理内存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() /
// 已使用的物理内存
long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
.getFreePhysicalMemorySize())
// 获得线程总数
ThreadGroup parentT
for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
.getParent() != parentThread = parentThread.getParent())
int totalThread = parentThread.activeCount();
double cpuRatio = 0;
if (osName.toLowerCase().startsWith("windows")) {
cpuRatio = this.getCpuRatioForWindows();
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 infoB
private static double getCpuRateForLinux(){
InputStream is =
InputStreamReader isr =
BufferedReader brStat =
StringTokenizer tokenStat =
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;
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);
} finally{
freeResource(is, isr, brStat);
private static void freeResource(InputStream is, InputStreamReader isr, BufferedReader br){
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使用率
* @author GuoHuang
private double getCpuRatioForWindows() {
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();
return 0.0;
} catch (Exception ex) {
ex.printStackTrace();
return 0.0;
* 读取CPU信息.
* @param proc
* @author GuoHuang
private long[] readCpu(final Process proc) {
long[] retn = new long[2];
proc.getOutputStream().close();
InputStreamReader ir = new InputStreamReader(proc.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line = input.readLine();
if (line == null || line.length() & FAULTLENGTH) {
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) {
// 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount,
// ThreadCount,UserModeTime,WriteOperation
String caption = Bytes.substring(line, capidx, cmdidx - 1)
String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") &= 0) {
// ("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();
kneltime += Long.valueOf(
Bytes.substring(line, kmtidx, rocidx - 1).trim())
.longValue();
usertime += Long.valueOf(
Bytes.substring(line, umtidx, wocidx - 1).trim())
.longValue();
retn[1] = kneltime +
} catch (Exception ex) {
ex.printStackTrace();
} finally {
proc.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
* @param args
* @throws Exception
* @author GuoHuang
public static void main(String[] args) throws Exception {
IMonitorService service = new MonitorServiceImpl();
MonitorInfoBean monitorInfo = service.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");
其中,Bytes类用来处理字符串
public class Bytes {
public static String substring(String src, int start_idx, int end_idx){
byte[] b = src.getBytes();
String tgt = "";
for(int i=start_ i&=end_ i++){
tgt +=(char)b[i];
浏览 31011
getTotalPhysicalMemorySize()getFreePhysicalMemorySize()均只能获取到一根内存条的容量错了,仅是getTotalPhysicalMemorySize()方法
yongyuan.jiang
浏览: 355877 次
来自: 深圳
放在自己工程上不报错,已放在服务器上就报错
能运行?我报错啊、
yue_ch 写道getTotalPhysicalMemory ...
getTotalPhysicalMemorySize()get ...
private RealSubject realSubject ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'博客分类:
FROM:http://bingoffice./blog/static//
Runtime 类:每个Java应用程序都有一个Runtime类实例,使应用程序能够与其运行的环境相连接。应用程序不能创建自己的 Runtime 类实例,可以通过getRuntime()方法获取当前运行时。 Properties 类:Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。list(PrintStream out)或者list(PrintWriter out)方法将属性列表输出到指定的输出流。System 类:System 类包含一些有用的类字段和方法。它不能被实例化。在 System 类提供的设施中,有标准输入、标准输出和错误输出流;对外部定义的属性和环境变量的访问;加载文件和库的方法;还有快速复制数组的一部分的实用方法。getProperties()方法确定当前的系统属性。
import java.util.P//导入Properties类public class SystemInfo{ public static void main(String args[]){
Properties p=System.getProperties();//获取当前的系统属性
p.list(System.out);//将属性列表输出
System.out.print("CPU个数:");//Runtime.getRuntime()获取当前运行时的实例
System.out.println(Runtime.getRuntime().availableProcessors());//availableProcessors()获取当前电脑CPU数量
System.out.print("虚拟机内存总量:");
System.out.println(Runtime.getRuntime().totalMemory());//totalMemory()获取java虚拟机中的内存总量
System.out.print("虚拟机空闲内存量:");
System.out.println(Runtime.getRuntime().freeMemory());//freeMemory()获取java虚拟机中的空闲内存量
System.out.print("虚拟机使用最大内存量:");
System.out.println(Runtime.getRuntime().maxMemory());//maxMemory()获取java虚拟机试图使用的最大内存量 }}
方法简单实用,虽然不是经常用,但是还是有必要去了解一下,因为不可能每次遇到不会的都拿出字典来查阅。但搞开放最重要的是拿到资料会运用,我们也不可能把所有的类、方法和属性等全部记住,所以要会看API和应用。
在本例中,我们要获取系统信息,要用到Properties类,首先要创建一个Properties对象,然后通过System类的getProperties()方法获取当前系统的信息。然后把获取到的系统属性交给Properties对象,该对象保存着系统信息的集合。最后由Properties类的list方法,把信息输出。Runtime类的几个方法可以相应的获取其他的信息。只要我们熟悉这些方法,自然能应用。
下面将介绍System.getProperty 系统参数:
Properties props=System.getProperties(); //系统属性 System.out.println("Java的运行环境版本:"+props.getProperty("java.version")); System.out.println("Java的运行环境供应商:"+props.getProperty("java.vendor")); System.out.println("Java供应商的URL:"+props.getProperty("java.vendor.url")); System.out.println("Java的安装路径:"+props.getProperty("java.home")); System.out.println("Java的虚拟机规范版本:"+props.getProperty("java.vm.specification.version")); System.out.println("Java的虚拟机规范供应商:"+props.getProperty("java.vm.specification.vendor")); System.out.println("Java的虚拟机规范名称:"+props.getProperty("java.vm.specification.name")); System.out.println("Java的虚拟机实现版本:"+props.getProperty("java.vm.version")); System.out.println("Java的虚拟机实现供应商:"+props.getProperty("java.vm.vendor")); System.out.println("Java的虚拟机实现名称:"+props.getProperty("java.vm.name")); System.out.println("Java运行时环境规范版本:"+props.getProperty("java.specification.version")); System.out.println("Java运行时环境规范供应商:"+props.getProperty("java.specification.vender")); System.out.println("Java运行时环境规范名称:"+props.getProperty("java.specification.name")); System.out.println("Java的类格式版本号:"+props.getProperty("java.class.version")); System.out.println("Java的类路径:"+props.getProperty("java.class.path")); System.out.println("加载库时搜索的路径列表:"+props.getProperty("java.library.path")); System.out.println("默认的临时文件路径:"+props.getProperty("java.io.tmpdir")); System.out.println("一个或多个扩展目录的路径:"+props.getProperty("java.ext.dirs")); System.out.println("操作系统的名称:"+props.getProperty("os.name")); System.out.println("操作系统的构架:"+props.getProperty("os.arch")); System.out.println("操作系统的版本:"+props.getProperty("os.version")); System.out.println("文件分隔符:"+props.getProperty("file.separator"));
//在 unix 系统中是"/" System.out.println("路径分隔符:"+props.getProperty("path.separator"));
//在 unix 系统中是":" System.out.println("行分隔符:"+props.getProperty("line.separator"));
//在 unix 系统中是"/n" System.out.println("用户的账户名称:"+props.getProperty("user.name")); System.out.println("用户的主目录:"+props.getProperty("user.home")); System.out.println("用户的当前工作目录:"+props.getProperty("user.dir"));
浏览: 324926 次
来自: 上海
CPU型号怎么弄?
你好,我需要FishermanJCE,请问能发份这个包给我么? ...
你好,我也需要这个例子的依赖的FishermanJCE相关的包 ...
json序列化反序列化插件-json2.js 介绍和使用 -
FishermanJCE 是山东渔翁公司加密卡提供调用加密机/ ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'Advertisement&>&长轮询查看服务器cpu的利用率
长轮询查看服务器cpu的利用率
上传大小:5.12MB
该Demo是一个简单的通过ajax+struts2写的长轮询,通过服务器得到新的数据,直接推送给浏览器的小Demo,希望大家相互学习
综合评分:4.5(2位用户评分)
所需积分/C币:
下载个数:20
{%username%}回复{%com_username%}{%time%}\
/*点击出现回复框*/
$(".respond_btn").on("click", function (e) {
$(this).parents(".rightLi").children(".respond_box").show();
e.stopPropagation();
$(".cancel_res").on("click", function (e) {
$(this).parents(".res_b").siblings(".res_area").val("");
$(this).parents(".respond_box").hide();
e.stopPropagation();
/*删除评论*/
$(".del_comment_c").on("click", function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_invalid/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parents(".conLi").remove();
alert(data.msg);
$(".res_btn").click(function (e) {
var q = $("#form1").serializeArray();
console.log(q);
var res_area_r = $.trim($(".res_area_r").val());
if (res_area_r == '') {
$(".res_text").css({color: "red"});
$.post("/index.php/comment/do_comment_reply/", q,
function (data) {
if (data.succ == 1) {
var $target,
evt = e || window.
$target = $(evt.target || evt.srcElement);
var $dd = $target.parents('dd');
var $wrapReply = $dd.find('.respond_box');
console.log($wrapReply);
var mess = $(".res_area_r").val();
var str = str.replace(/{%header%}/g, data.header)
.replace(/{%href%}/g, 'http://' + window.location.host + '/user/' + data.username)
.replace(/{%username%}/g, data.username)
.replace(/{%com_username%}/g, _username)
.replace(/{%time%}/g, data.time)
.replace(/{%id%}/g, data.id)
.replace(/{%mess%}/g, mess);
$dd.after(str);
$(".respond_box").hide();
$(".res_area_r").val("");
$(".res_area").val("");
$wrapReply.hide();
alert(data.msg);
}, "json");
/*删除回复*/
$(".rightLi").on("click",'.del_comment_r', function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_comment_del/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parent().parent().parent().parent().parent().remove();
$(e.target).parents('.res_list').remove()
alert(data.msg);
//填充回复
function KeyP(v) {
$(".res_area_r").val($.trim($(".res_area").val()));
评论共有1条
可以,先看看。
审核通过送C币
FastJson、Gson、Jackson的JSON类库jar包合集
创建者:chenchunlin526
Openfire源码缺失的jar包列表
创建者:songxinfeng1989
精选6套分布式相关视频
创建者:love
上传者其他资源上传者专辑
spring + struts2 + hibernate 用在一个项目中的核心包
开发技术热门标签
VIP会员动态
下载频道用户反馈专区
下载频道积分规则调整V1710.18
开通VIP,海量IT资源任性下载
spring mvc+mybatis+mysql+maven+bootstrap 整合实现增删查改简单实例.zip
CSDN&VIP年卡&4000万程序员的必选
为了良好体验,不建议使用迅雷下载
长轮询查看服务器cpu的利用率
会员到期时间:
剩余下载个数:
剩余C币:593
剩余积分:0
为了良好体验,不建议使用迅雷下载
积分不足!
资源所需积分/C币
当前拥有积分
您可以选择
程序员的必选
绿色安全资源
资源所需积分/C币
当前拥有积分
当前拥有C币
(仅够下载10个资源)
全站1200个资源免积分下载
为了良好体验,不建议使用迅雷下载
资源所需积分/C币
当前拥有积分
当前拥有C币
全站600个资源免积分下载
资源所需积分/C币
当前拥有积分
当前拥有C币
您的积分不足,将扣除 10 C币
全站1200个资源免积分下载
为了良好体验,不建议使用迅雷下载
你当前的下载分为234。
你还不是VIP会员
开通VIP会员权限,免积分下载
你下载资源过于频繁,请输入验证码
你下载资源过于频繁,请输入验证码
您因违反CSDN下载频道规则而被锁定帐户,如有疑问,请联络:!
若举报审核通过,可奖励20下载分
被举报人:
举报的资源分:
请选择类型
资源无法下载
资源无法使用
标题与实际内容不符
含有危害国家安全内容
含有反动色情等内容
含广告内容
版权问题,侵犯个人或公司的版权
*详细原因:
长轮询查看服务器cpu的利用率

我要回帖

更多关于 java linux cpu使用率 的文章

 

随机推荐