分别有开始,暂停,继续按扭,当点击开始按钮时启动线程,当点击暂停按钮时挂起线程,当点击继续按钮时继续执行刚才挂起的线程,
请问怎么实现

解决方案 »

  1.   

    如果只是一个线程的话。使用wait
    wait()导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法
      

  2.   

    这个画图程序可能对你有所帮助
    import java.awt.*;
    import java.awt.event.*;
    public class DrawRectTest2 extends Frame implements Runnable{
    private Color[] colors={Color.red,Color.blue,Color.green,Color.orange};
    private Color color;
    int count1=0;
    int count2=0;
    int count3=0;
    Thread t=new Thread(this);
    Boolean bool=true;
    int x=0,y=0,lengsize=100,widthsize=100;
    private int[][] sizes={{50,50},{170,50},{50,170},{170,170}};public DrawRectTest2(String title){
    super(title);
    addMouseListener(new MouseAdapter(){
    public void mousePressed(MouseEvent event){
    if(bool==true){
    bool=false;
    //t.interrupt();
    }
    else{
    bool=true;//如何恢复
    //t.run();
    }
    }
    });
    addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    }
    });
    setSize(300,300);
    setVisible(true);
    t.start();
    }public void run(){
    while(true){
        while(bool);
    color=colors[count1++%colors.length];
    x=sizes[count2++%4][0];
    y=sizes[count3++%4][1];
    repaint();
    try{
    Thread.sleep(1000);
    }
    catch(InterruptedException e){}
    }
    }public void paint(Graphics g){
    g.setColor(color);
    g.drawRect(x,y,lengsize,widthsize);
    }public static void main(String args[])throws Exception{
    new DrawRectTest2("hello");
    }}
      

  3.   

    刚开始线程使用 Thread.start();暂停或重启可以如下使用private boolean suspend=false;public void run(){
      while(true){
        if(suspend){//暂停
          sleep(1000);
        }else{
         //正常执行代码
         }
       }
    }
    //重启或者暂停
    public void turn(){
      suspend=suspend?false:true;
    }
      

  4.   

    用wait怎么实现啊,是这样的该线程循环打印1,2,3,4等打印到2时我点击暂停按钮后线程就在2处了,等到我点击
    继续按钮线程接着打印3,4