线程停止不了
package com.soft.test;import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class StopFrame extends JFrame implements ActionListener{
private JPanel jPanel;
private JScrollPane scrollPane;
private JTextArea area;
private JButton button;
private CirStopThread cirStopThread;
private Thread thread;
public StopFrame(){
init();
setTitle("线程停止");
setSize(600,500);
cirStopThread=new CirStopThread(area);
thread=new Thread(cirStopThread);
thread.start();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
public void init(){
jPanel=new JPanel(new FlowLayout(FlowLayout.CENTER));
button=new JButton("停止");
button.addActionListener(this);
area=new JTextArea(10,25);
scrollPane=new JScrollPane(area);
jPanel.add(scrollPane);
jPanel.add(button);
add(jPanel,BorderLayout.CENTER);
}
public static void main(String[] args) {
new StopFrame();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button){
if(cirStopThread.isFlag()==true){
cirStopThread.setFlag(false);
button.setText("开始");
System.out.println(cirStopThread.isFlag());
}
else {
cirStopThread.setFlag(true);
thread=new Thread(cirStopThread);
thread.start();
button.setText("停止");
System.out.println(cirStopThread.isFlag());
}
}
}
}
****************
package com.soft.test;
import javax.swing.JTextArea;
public class CirStopThread implements Runnable{
private JTextArea jTextArea;
private boolean flag=true;
public boolean isFlag(){
return flag;
}
public void setFlag(boolean flag){
this.flag=flag;
}
public CirStopThread(JTextArea area) {
this.jTextArea=area;
}
@Override
public void run() {
String str[]={"Mary","Rose","Jack"};
int len=str.length;
while(flag)
{
for(int i=0;i>=0;i++){
int n=i%len;
jTextArea.append(str[n]+"\r\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}