0

我一直在尝试编写一个简单的 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);
    }
}

谢谢!

4

1 回答 1

1

经过更多的实验,我发现该程序正在冻结,因为它正在寻找特定于操作系统和体系结构的 SIGAR 库。在这种情况下,它需要 64 位通用 Mac OS X 驱动程序。然而,SIGAR 将这些作为 .dylib 文件提供,Eclipse 拒绝加载这些文件。.dylib 文件必须打包在一个 .zip 存档中,然后将其添加到 Eclipse 构建路径中。

于 2013-02-15T04:42:28.987 回答