通过对话框中的两个按钮来控制程序的执行,start按钮开启线程,stop按钮停止线程。可是开启线程后,在调用stop按钮停止线程,就是停止不了,对话框也关不掉。import javax.swing.*;
import java.awt.event.*;
import java.awt.*;public class Exple
{
public static void main(String[] args)
{
Exple gui = new Exple();
gui.go();
}
public void go()
{
JFrame frame = new JFrame();
JButton startButton = new JButton("启动");
startButton.addActionListener(new StartListener());
JButton stopButton = new JButton("停止");
stopButton.addActionListener(new StopListener()); frame.getContentPane().add(BorderLayout.WEST,stopButton);
frame.getContentPane().add(BorderLayout.EAST,startButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
} private volatile boolean flag=true;
//启动
class StartListener implements ActionListener{
public void actionPerformed(ActionEvent event)
{
while (flag)
{
System.out.println("doJob");
}
}
}
//停止
class StopListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
flag = false;
}
}
}
import java.awt.event.*;
import java.awt.*;public class Exple
{
public static void main(String[] args)
{
Exple gui = new Exple();
gui.go();
}
public void go()
{
JFrame frame = new JFrame();
JButton startButton = new JButton("启动");
startButton.addActionListener(new StartListener());
JButton stopButton = new JButton("停止");
stopButton.addActionListener(new StopListener()); frame.getContentPane().add(BorderLayout.WEST,stopButton);
frame.getContentPane().add(BorderLayout.EAST,startButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
} private volatile boolean flag=true;
//启动
class StartListener implements ActionListener{
public void actionPerformed(ActionEvent event)
{
while (flag)
{
System.out.println("doJob");
}
}
}
//停止
class StopListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
flag = false;
}
}
}
而在线程中使用isIntercept()方法判断当前线程是否已经中断
flag = true;
t = new Thread()
{
public void run()
{
while( flag )
{
}
}
}//开始
*****
t.start();
*****
//结束
*****
flag = false;
*****