AWT事件线程中断 - CPU负载不良

时间:2013-12-14 23:51:33

标签: java multithreading awt event-dispatch-thread interruption

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

为什么会这样?

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");
        }
    }
}

0 个答案:

没有答案