简体   繁体   English

使用GUI启动线程(Java)

[英]Starting a thread with the GUI (Java)

My GUI freezes whenever the run method in the thread is called, does anybody know why? 每当调用线程中的run方法时,我的GUI都会冻结,有人知道为什么吗?

Main : 主要:

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 method from thread: 从线程运行方法:

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

actionListener that is supposed to start the thread: 应该启动线程的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");
    }
}

} }

That's because the run() method does not start a new thread. 这是因为run()方法不会启动新线程。 Assuming your robot reference refers to an instance of Runnable you need to call the following; 假设您的robot引用引用了Runnable的实例,则需要调用以下代码;

new Thread(robot).start();

Calling start() will start a new thread, and call the run() method on it. 调用start()将启动一个新线程,并在其上调用run()方法。 Currently your run() method is being run on the same thread it is called from (in your instance the event dispatch thread). 当前,您的run()方法正在从其调用的同一线程上运行(在您的实例中为事件调度线程)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM