我一直在尝试编写一个简单的 CPU 利用率监视器作为大型项目的概念证明。我正在用 Eclipse Juno 写作。当我按下“运行”时,我的应用程序按预期工作——CPU 利用率显示为每秒更新一次的百分比。但是,当我将它导出到可执行 jar 时,应用程序似乎被锁定了——它从不显示百分比,也从不更新。我已经确定 GUI 很好,但是由于某些莫名其妙的原因,我的 cpuUtilization 方法永远不会返回百分比而不会抛出异常。更奇怪的是,这个问题只发生在程序导出时。SIGAR 的文档非常糟糕,但我认为我正确使用了它。程序的所有其余部分似乎都可以工作,所以我只包含 CPUReader 类。它是在构造CPUMonitorGUI类时构造的,CPUMonitorGUI每秒调用一次cpuUtilization。一些附加说明:我导入了 sigar.jar 但没有导入 log4j.jar。这样做没有任何区别。此外,在 Eclipse 中,我在导出时选择了“将所需的库打包到生成的 JAR 中”。
package cpuperc;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Humidor;
import org.hyperic.sigar.SigarProxy;
public class CPUReader
{
static Humidor h;
public CPUReader()
{
h = Humidor.getInstance();
}
public double cpuUtilization() throws SigarException
{
//Returns CPU utilization as truncated two-decimal percent
SigarProxy sp = h.getSigar();
CpuPerc cp = sp.getCpuPerc();
double combined;
double total;
double idle;
double percentUsed;
int truncate = 0;
//get CPU times
combined = cp.getCombined();
idle = cp.getIdle();
total = idle + combined;
//determine percent and truncate
percentUsed = ((double)combined/total)*100;
truncate = (int)(percentUsed*100.0);
percentUsed = (double)truncate/100;
return(percentUsed);
}
}
谢谢!