【问题标题】:Starting a thread with the GUI (Java)使用 GUI (Java) 启动线程
【发布时间】:2014-07-15 09:24:41
【问题描述】:

每当调用线程中的 run 方法时,我的 GUI 就会冻结,有人知道为什么吗?

主要:

try {
        // Set System Look and Feel
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (UnsupportedLookAndFeelException e) {
        // handle exception
    } catch (ClassNotFoundException e) {
        // handle exception
    } catch (InstantiationException e) {
        // handle exception
    } catch (IllegalAccessException e) {
        // handle exception
    }
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainFrame frame = new MainFrame(null, null);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

从线程运行方法:

public void run() {
    while (true) {
        System.out.println("test");
    }
}

应该启动线程的actionListener:

private ActionListener btnStartListener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        robot.run();
    }
};




public class RobotThread implements Runnable {
@Override
public void run() {
    while (true) {
        System.out.println("test");
    }
}

}

【问题讨论】:

    标签: java multithreading user-interface


    【解决方案1】:

    那是因为run() 方法没有启动一个新线程。假设您的 robot 引用引用了 Runnable 的实例,您需要调用以下代码;

    new Thread(robot).start();
    

    调用start() 将启动一个新线程,并在其上调用run() 方法。目前,您的 run() 方法正在调用它的同一线程上运行(在您的实例中为事件调度线程)。

    【讨论】:

    • +1 for run() 没有启动一个新线程 - 但在 swing 时它是事件调度线程而不是主线程,这会导致 UI 冻结。
    • 是的,robot 是指 Runnable 的一个实例。我试过你的答案,但 run() 中的代码现在没有被执行。
    • @user3742929 - 你在哪里定义了robot 所指的Runnable?也许你的 Runnable 的 run() 方法不是有效的覆盖或类似的东西。
    • 我刚刚将您的代码添加到我的 IDE 并使用了new Thread(new RobotThread()).start();,它运行良好。是否还有其他我们遗漏的细节,例如robot 的声明和实例化位置?也就是说,你不应该在没有调用 Thread.sleep(x); 的情况下使用 while(true){},否则 while 循环可能会使用所有可用的 CPU 资源并阻止其他所有内容。
    • 我复制了 new Thread(new RobotThread()).start();它突然起作用了,不知道我的错误是什么。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多