[英]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");
}
}
}
這是因為run()
方法不會啟動新線程。 假設您的robot
引用引用了Runnable
的實例,則需要調用以下代碼;
new Thread(robot).start();
調用start()
將啟動一個新線程,並在其上調用run()
方法。 當前,您的run()
方法正在從其調用的同一線程上運行(在您的實例中為事件調度線程)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.