第一份源代码:
package thread;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Main extends JFrame implements ActionListener
{ /**
 * @param args
 */
JButton btn_start;
JButton btn_pause;
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("start...........");
Main m=new Main();
m.setVisible(true);
m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public Main()
{
setSize(400,300);
setTitle("this is test");
getContentPane().setLayout(new FlowLayout());
getContentPane().add(btn_start=new JButton("start"));
getContentPane().add(btn_pause=new JButton("pause"));
btn_start.addActionListener(this);
btn_pause.addActionListener(this);

}
@Override
public void actionPerformed(ActionEvent e)
{
PaintNumber num=new PaintNumber();
if(e.getSource()==btn_start)
{
num.start();
}
if(e.getSource()==btn_pause)
{
num.pause();
}

}}第二份源代码:package thread;public class PaintNumber extends Thread
{
int i =1;
static boolean flag=true;
public void run()
{
try
{
while(flag)
{
System.out.println(i++);
Thread.sleep(500);
}
}catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
@SuppressWarnings("static-access")
public void pause()
{
//this.flag=false;
try
{
//synchronized(this)
{
this.wait();//报错
}
                        //this.susuped(); 此项没用
                        //this.yield(); //此项也没有用
}catch(InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}
现在的问题是:为什么不能暂停或中断

解决方案 »

  1.   

    @Override
        public void actionPerformed(ActionEvent e)
        {
            PaintNumber num=new PaintNumber();
            if(e.getSource()==btn_start)
            {
                num.start();
            }
            if(e.getSource()==btn_pause)
            {
                num.pause();
            }
            
        }没见你调用这个方法啊??这个方法是控制暂停的啊??你在哪里调用的??
      

  2.   

    public void actionPerformed(ActionEvent e)
        {
            PaintNumber num=new PaintNumber();
            if(e.getSource()==btn_start)
            {
                num.start();
            }
            if(e.getSource()==btn_pause)
            {
                num.pause();
            }
            
        }
    你每次点击按钮,都会新生成一个num对象,比如说你按暂停,你按后,它生成一个num,然后把这个暂停.可是你上次生成的num,你已经无法控制了.嘿嘿
      

  3.   

    public viod pause{
       flag=false;}
      

  4.   

     //synchronized(this)
                {
                    this.wait();//报错
                }   this.wait()必须在synchronized 的括号里