I have a form
public class MainFrame extends JFrame {
private int colThread=0;
MainThread mt=new MainThread("Поток - 1");
public MainFrame()
{
setSize(300,300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
JButton jb=new JButton("Запустить поток");
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
jb.setText("Перезапустить поток");
colThread = colThread + 1;
if (!mt.isInterrupted())
{
mt.interrupt();
}
mt.start();
}
});
jp.add(jb);
add(jp);
}
}
I have a thread class:
public class MainThread extends Thread{
private int summ;
private String threadName;
public MainThread(String threadName)
{
this.threadName = threadName;
}
@Override
public void run() {
summ = 0;
while(true)
{
summ = summ +1;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.threadName + " " + summ);
}
}
}
I have the main class:
public class MainClass {
public static void main(String[] args) {
MainFrame mf = new MainFrame();
mf.setVisible(true);
}
}
The question is how to restart the thread execution when the button is clicked. When executing the program in this form, an error occurs, but this is understandable, because the thread works, it is not clear why interrupt () does not work?