使用GUI(Java)启动一个线程

use*_*929 1 java user-interface multithreading

每当调用线程中的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();
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

从线程运行方法:

public void run() {
    while (true) {
        System.out.println("test");
    }
}
Run Code Online (Sandbox Code Playgroud)

应该启动线程的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");
    }
}
Run Code Online (Sandbox Code Playgroud)

}

Rud*_*haw 5

那是因为该run()方法不会启动新线程.假设您的robot引用是指Runnable您需要调用以下内容的实例;

new Thread(robot).start();
Run Code Online (Sandbox Code Playgroud)

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