Hyperic Sigar API - 无法在runnable jar文件中运行

时间:2016-02-04 17:13:48

标签: java memory cpu sigar hyperic

以下是CPU和内存计的代码。它在eclipse mars 1中效果很好但在制作可运行的jar时不起作用。刚出现一个带有两个标签CPU和RAM的JFrame,不会给出百分比值。

请帮忙。 谢谢。

    package main;

import javax.swing.JLabel;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

public class MemoryThread implements Runnable {
    private static Thread memoryThread;
    private static String threadName;
    private static Sigar sigar;
    public static JLabel txtRAMUsage = new JLabel("RAM");
    public static JLabel txtCPUUsage = new JLabel("CPU");

    public MemoryThread(String name) {
        threadName = name;
    }

    private static long[] getMemory() {
        Mem mem = null;
        CpuPerc cpu = null;
        try {
            mem = sigar.getMem();
            // long pid = sigar.getPid();
            cpu = sigar.getCpuPerc();
        } catch (SigarException se) {
            se.printStackTrace();
        }

        long[] memories = new long[2];

        memories[0] = (long) (mem.getUsedPercent() + 2);
        memories[0] = memories[0] < 100 ? memories[0] : 100;

        memories[1] = (long) (cpu.getCombined() * 100) + 5;
        memories[1] = memories[1] < 100 ? memories[1] : 100;

        return memories;
    }

    private static void runThread() throws InterruptedException {

        while (true) {
            long[] memories = getMemory();
            txtRAMUsage.setText("CPU: " + memories[1] + " %");
            txtCPUUsage.setText("RAM: " + memories[0] + " %");
            Thread.sleep(1000);
        }
    }

    @Override
    public void run() {
        try {
            runThread();
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Thread " + threadName + " interrupted.");
        }
    }

    public void start() {
        if (memoryThread == null) {
            sigar = new Sigar();
            memoryThread = new Thread(this, threadName);
            memoryThread.start();
        }
    }

    /*
     * public static void main(String args[]){ MemoryThread mt = new
     * MemoryThread("RAM"); mt.start(); }
     */
}

0 个答案:

没有答案