通过对话框中的两个按钮来控制程序的执行,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;
}
 

}
   
 

解决方案 »

  1.   

    你根本没有新开线程,点start就直接死循环了。建议还是先看看书吧,多数书上都应该有线程的章节的,你若看过,就不会写出这样的程序来了...
      

  2.   

    可以调用线程的intercept()方法将启动的线程中断
    而在线程中使用isIntercept()方法判断当前线程是否已经中断
      

  3.   

    Thread t = null;
    flag = true;
    t = new Thread()
    {
         public void run()
         {
               while( flag )
                {
                 }
          }
    }//开始
    *****
         t.start();
    *****
    //结束
    *****
    flag = false;
    *****