0

当 AWT 事件线程在 sleep() 或 wait() 之后通过在 UI 上执行操作而被中断时,会导致正在运行的 java 进程(Windows 7,JRE 1.7.0_05)导致 CPU 负载不佳(25-30%)。

为什么会这样?

package main;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;

public class Main {

    public static void main(String[] args) {
        try {
            Main client = new Main();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    private Main() throws Exception {
        if (!SystemTray.isSupported()) {
            throw new Exception("System tray is not supported");
        }

        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("icon.png");
        Image img = ImageIO.read(is);
        is.close();

        TrayIcon icon = new TrayIcon(img, "Application");
        SystemTray tray = SystemTray.getSystemTray();

        MenuItem mi = new MenuItem("Connect");

        PopupMenu menu = new PopupMenu();
        menu.add(mi);
        icon.setPopupMenu(menu);

        mi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    Thread.sleep(2500);
                    Thread.currentThread().interrupt();
                } catch (InterruptedException ex) {
                }
            }
        });

        try {
            tray.add(icon);
        } catch (AWTException e) {
            throw new Exception("Tray icon could not be added");
        }
    }
}
4

0 回答 0