使用GUI(Java)启动一个线程(Starting a thread with the GUI (Java))

编程入门 行业动态 更新时间:2024-10-26 03:37:01
使用GUI(Java)启动一个线程(Starting a thread with the GUI (Java))

每当调用线程中的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).

更多推荐

本文发布于:2023-08-06 05:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1444601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   Java   GUI   Starting   thread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!