如何获取java程序当前的使用内存

如何获取java程序当前的使用内存,第1张

方法如下:

首先

创建一个Bean用来存贮要得到的信

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) {

thisfreeMemory = freeMemory;

}

public long getFreePhysicalMemorySize() {

return freePhysicalMemorySize;

}

public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {

thisfreePhysicalMemorySize = freePhysicalMemorySize;

}

public long getMaxMemory() {

return maxMemory;

}

public void setMaxMemory(long maxMemory) {

thismaxMemory = maxMemory;

}

public String getOsName() {

return osName;

}

public void setOsName(String osName) {

thisosName = osName;

}

public long getTotalMemory() {

return totalMemory;

}

public void setTotalMemory(long totalMemory) {

thistotalMemory = totalMemory;

}

public long getTotalMemorySize() {

return totalMemorySize;

}

public void setTotalMemorySize(long totalMemorySize) {

thistotalMemorySize = totalMemorySize;

}

public int getTotalThread() {

return totalThread;

}

public void setTotalThread(int totalThread) {

thistotalThread = totalThread;

}

public long getUsedMemory() {

return usedMemory;

}

public void setUsedMemory(long usedMemory) {

thisusedMemory = usedMemory;

}

public double getCpuRatio() {

return cpuRatio;

}

public void setCpuRatio(double cpuRatio) {

thiscpuRatio = cpuRatio;

}

}

之后,建立bean的接口

public interface IMonitorService {

public MonitorInfoBean getMonitorInfoBean() throws Exception;

}

然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。

import javaioInputStreamReader;

import javaioLineNumberReader;

import sunmanagementManagementFactory;

import comsunmanagementOperatingSystemMXBean;

import javaio;

import javautilStringTokenizer;

/

获取系统信息的业务逻辑实现类

@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 = null;

/

获得当前的监控对象

@return 返回构造好的监控对象

@throws Exception

@author GuoHuang

/

public MonitorInfoBean getMonitorInfoBean() throws Exception {

int kb = 1024;

// 可使用内存

long totalMemory = RuntimegetRuntime()totalMemory() / kb;

// 剩余内存

long freeMemory = RuntimegetRuntime()freeMemory() / kb;

// 最大可使用内存

long maxMemory = RuntimegetRuntime()maxMemory() / kb;

OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory

getOperatingSystemMXBean();

// *** 作系统

String osName = SystemgetProperty("osname");

// 总的物理内存

long totalMemorySize = osmxbgetTotalPhysicalMemorySize() / kb;

// 剩余的物理内存

long freePhysicalMemorySize = osmxbgetFreePhysicalMemorySize() / kb;

// 已使用的物理内存

long usedMemory = (osmxbgetTotalPhysicalMemorySize() - osmxb

getFreePhysicalMemorySize())

/ kb;

// 获得线程总数

ThreadGroup parentThread;

for (parentThread = ThreadcurrentThread()getThreadGroup(); parentThread

getParent() != null; parentThread = parentThreadgetParent())

;

int totalThread = parentThreadactiveCount();

double cpuRatio = 0;

if (osNametoLowerCase()startsWith("windows")) {

cpuRatio = thisgetCpuRatioForWindows();

}

else {

cpuRatio = thisgetCpuRateForLinux();

}

// 构造返回对象

MonitorInfoBean infoBean = new MonitorInfoBean();

infoBeansetFreeMemory(freeMemory);

infoBeansetFreePhysicalMemorySize(freePhysicalMemorySize);

infoBeansetMaxMemory(maxMemory);

infoBeansetOsName(osName);

infoBeansetTotalMemory(totalMemory);

infoBeansetTotalMemorySize(totalMemorySize);

infoBeansetTotalThread(totalThread);

infoBeansetUsedMemory(usedMemory);

infoBeansetCpuRatio(cpuRatio);

return infoBean;

}

private static double getCpuRateForLinux(){

InputStream is = null;

InputStreamReader isr = null;

BufferedReader brStat = null;

StringTokenizer tokenStat = null;

try{

Systemoutprintln("Get usage rate of CUP , linux version: "+linuxVersion);

Process process = RuntimegetRuntime()exec("top -b -n 1");

is = processgetInputStream();

isr = new InputStreamReader(is);

brStat = new BufferedReader(isr);

if(linuxVersionequals("24")){

brStatreadLine();

brStatreadLine();

brStatreadLine();

brStatreadLine();

tokenStat = new StringTokenizer(brStatreadLine());

tokenStatnextToken();

tokenStatnextToken();

String user = tokenStatnextToken();

tokenStatnextToken();

String system = tokenStatnextToken();

tokenStatnextToken();

String nice = tokenStatnextToken();

Systemoutprintln(user+" , "+system+" , "+nice);

user = usersubstring(0,userindexOf("%"));

system = systemsubstring(0,systemindexOf("%"));

nice = nicesubstring(0,niceindexOf("%"));

float userUsage = new Float(user)floatValue();

float systemUsage = new Float(system)floatValue();

float niceUsage = new Float(nice)floatValue();

return (userUsage+systemUsage+niceUsage)/100;

}else{

brStatreadLine();

brStatreadLine();

tokenStat = new StringTokenizer(brStatreadLine());

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

String cpuUsage = tokenStatnextToken();

Systemoutprintln("CPU idle : "+cpuUsage);

Float usage = new Float(cpuUsagesubstring(0,cpuUsageindexOf("%")));

return (1-usagefloatValue()/100);

}

} catch(IOException ioe){

Systemoutprintln(ioegetMessage());

freeResource(is, isr, brStat);

return 1;

} finally{

freeResource(is, isr, brStat);

}

}

    在进行多线程编程中 比较重要也是比较困难的一个 *** 作就是如何获取线程中的信息 大多数人会采取比较常见的一种方法就是将线程中要返回的结果存储在一个字段中 然后再提供一个获取方法将这个字段的内容返回给该方法的调用者 如以下的ReturnThreadInfo类

  package threadtest ;/ @author shi mingxiang/public class ReturnThreadInfo extends Thread {private String str;public ReturnThreadInfo() {this str = Hello ;}public void run(){this str = Hello World! ;}public String getThreadInfo(){return this str;}}

    大家可以看到该类是一个线程类并含有一个初始值为 Hello 的字段str以及一个可以返回str值的方法 getThreadInfo() 而且当这个线程启动后str会被赋于新值 Hello World! 现在我想在另外一个类中启动ReturnThreadInfo线程 并通过getThreadInfo()方法获取值为 Hello World! 的变量并打印输出到控制台中 以下给出一个实现该功能的Main类

 package threadtest ;/ @author shi mingxiang/public class Main{public Main() {}/ @param args the mand line arguments /public static void main(String[] args) {ReturnThreadInfo returnThreadInfo = new ReturnThreadInfo();returnThreadInfo start(); //创建并启动ReturnThreadInfo线程System out println(returnThreadInfo getThreadInfo()); //获取并输出returnThreadInfo对象的str的值}}

lishixinzhi/Article/program/Java/gj/201311/27710

public class RandomNumber implements Runnable {

private final byte[] lock; // 同步对象锁

private Random random; // 用于生成随机数

private int sum; // 用于计算产生的随机数总数

public RandomNumber() {

lock = new byte[1];

random = new Random();

}

@Override

public void run() {

while (true) {

int rd = randomnextInt(1001); // 产生0 - 10000的随机数

if (rd == 0) {

continue;

} else {

if (sum >= 10000) {

return;

}

try {

Threadsleep(1); // 为了效果更明显,当前线程睡1毫秒

} catch (InterruptedException e) {

eprintStackTrace();

}

synchronized (lock) {

// 获取到对象锁之后,需要判断sum的大小,因为此时sum可能已经为10000了

if (sum < 10000) {

sum++;

Systemoutprintln(ThreadcurrentThread()getName()

+ " - 第" + sum + "个随机数:" + rd);

}

}

}

}

}

// main测试函数

public static void main(String[] args) throws Exception {

RandomNumber rn = new RandomNumber();

// 循环产生50个线程

for (int i = 0; i < 50; i++) {

new Thread(rn)start();

}

}

}

有问题再追问,一起学习探讨

获取线程名字这件事情本质上和Runnable是没有关系的。一个Runnable可以给多个线程去运行,所以如果在这个概念上你有误解的话,希望重新考虑一下。

另外,在任何时候,你都可以用ThreadcurrentThread()getName()来获取当前线程的名字

以上就是关于如何获取java程序当前的使用内存全部的内容,包括:如何获取java程序当前的使用内存、获取java线程中信息的两种方法[1]、JAVA采用实现Runnable接口的多线程技术,用50个线程,生成10000个[1-1000]间的随机整数。等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/10160226.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-05
下一篇 2023-05-05

发表评论

登录后才能评论

评论列表(0条)

保存