1

这是 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(); }
     */
}
4

0 回答 0