请告诉我有一个表格
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);
}
}
有一个流类:
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);
}
}
}
和主要课程:
public class MainClass {
public static void main(String[] args) {
MainFrame mf = new MainFrame();
mf.setVisible(true);
}
}
问题是如何在单击按钮时重新启动线程的执行。以这种形式执行程序时,会出现错误,不过这是可以理解的,因为线程在工作,不清楚为什么interrupt()不起作用?
根据Thread的描述,一个线程不能启动两次,可以通过Runnable解决,只需要考虑到如果线程是循环的,那么需要停止,否则会出现两个线程同时