启动新线程时出现非法线程状态异常

时间:2015-03-07 17:13:11

标签: java swing

尝试终止一个线程,然后开始一个新的线程,但是当我开始新的线程后,如果想要摆脱另一个线程,它会抛出一个IllegalThreadStateException。任何帮助将不胜感激,因为我对线程事物有点新意。谢谢。

public class Start_btn_Listener extends JButton implements ActionListener {
/*
 * ActionListener for the Start button in which starts the pendulum animation by creating a new thread.
 */

static volatile Thread p =new Thread(GUI.shm_panel);







@Override
public void actionPerformed(ActionEvent e) {

    if(!GUI.GetRunning()){ // Determines whether a thread of Pendulum_Swing is already running.
    p.start();
    GUI.running = true;
    }
    else{
        JLabel message = new JLabel("Pendulum is already running");
        Object[] options = {"OK"};
        final JOptionPane pane = new JOptionPane(message, JOptionPane.ERROR_MESSAGE, JOptionPane.OK_OPTION, null, options);
        JDialog dialog = pane.createDialog(GUI.shm_panel, "Running");
        message.requestFocus();
        dialog.setVisible(true);
         /*
          * Displays an error message when the Start button is clicked but the pendulum is still going.
          * Longer than usual to remove the focus border from the OK button as it always bugs me.
          */

    }

}
public static Thread GetThread(){
    return p;
}
}

1 个答案:

答案 0 :(得分:0)

你正在开始你的p线程,如:

p.start();

在某些事件上。您无法启动已启动,即运行或关闭线程。

您需要执行以下操作:

p =new Thread(GUI.shm_panel);
p.start();