提供一套開箱即用的 Java 記憶體監視視覺化工具,採用 Swing 構建 GUI,獨立執行緒輪詢 Runtime.getRuntime() 獲取堆記憶體使用狀況,以進度條與數值雙重呈現,適合開發階段即時觀察記憶體趨勢與 GC 效果。
JMemoryDemo:程式入口,建立主視窗並置中顯示MainFrame:主視窗,包含垂直進度條、狀態標籤、標題標籤ProgressThread:監控執行緒,每秒更新記憶體統計並刷新 UI
public class JMemoryDemo {
public static void main(String[] args) { new JMemoryDemo(); }
public JMemoryDemo() {
MainFrame frame = new MainFrame();
frame.setVisible(true);
// 視窗置中邏輯...
}
}
public class MainFrame extends JFrame {
private JProgressBar jProgressBar1 = new JProgressBar();
private JLabel jLabel1 = new JLabel("Memory Monitor");
private JLabel jLabel2 = new JLabel();
public MainFrame() {
setTitle("JMemoryDemo");
setSize(304, 215);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jProgressBar1.setOrientation(JProgressBar.VERTICAL);
jProgressBar1.setStringPainted(true);
jProgressBar1.setFont(new Font("Dialog", Font.PLAIN, 14));
// 佈局:北標題、中進度條、南狀態
getContentPane().setLayout(new BorderLayout());
getContentPane().add(jLabel1, BorderLayout.NORTH);
getContentPane().add(jProgressBar1, BorderLayout.CENTER);
getContentPane().add(jLabel2, BorderLayout.SOUTH);
new ProgressThread(jProgressBar1, jLabel2).start();
}
protected void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) System.exit(0);
super.processWindowEvent(e);
}
}
public class ProgressThread extends Thread {
private JProgressBar pbar; private JLabel label;
public ProgressThread(JProgressBar pbar, JLabel label) { this.pbar = pbar; this.label = label; }
public void run() {
pbar.setMinimum(0); pbar.setMaximum(100);
while (true) {
long total = Runtime.getRuntime().totalMemory() / 1024; // KB
long free = Runtime.getRuntime().freeMemory() / 1024;
int usedPercent = (int) ((total - free) * 100 / total);
label.setText(String.format("Free Memory: %dK Total Allocated: %dK", free, total));
pbar.setValue(100 - usedPercent); // 顯示剩餘百分比
pbar.setString("Free Memory " + (100 - usedPercent) + "%");
try { sleep(1000); } catch (InterruptedException ignored) {}
}
}
}
| 方法 | 含義 | 單位 |
|---|---|---|
Runtime.getRuntime().totalMemory() | JVM 當前向作業系統申請的總堆記憶體 | Bytes |
Runtime.getRuntime().freeMemory() | 當前堆中可用空間 | Bytes |
Runtime.getRuntime().maxMemory() | JVM 最大可使用堆記憶體(-Xmx) | Bytes |