每当调用线程中的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"); } }}
My GUI freezes whenever the run method in the thread is called, does anybody know why?
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:
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()方法没有启动新线程。 假设您的robot引用是指Runnable一个实例,您需要调用以下内容;
new Thread(robot).start();调用start()将启动一个新线程,并在其上调用run()方法。 目前,您的run()方法正在调用它的同一个线程上运行(在您的实例中是事件派发线程)。
That's because the run() method does not start a new thread. Assuming your robot reference refers to an instance of Runnable you need to call the following;
new Thread(robot).start();Calling start() will start a new thread, and call the run() method on it. Currently your run() method is being run on the same thread it is called from (in your instance the event dispatch thread).
更多推荐
发布评论