2013-09-21 112 views
3

我做了一个倒数计时器,并且假设“停止”按钮停止倒计时并重置文本字段。如何停止线程?

class Count implements Runnable { 
    private Boolean timeToQuit=false; 

    public void run() { 
     while(!timeToQuit) { 
      int h = Integer.parseInt(tHrs.getText()); 
      int m = Integer.parseInt(tMins.getText()); 
      int s = Integer.parseInt(tSec.getText()); 
      while(s>=0) { 
       try { 
        Thread.sleep(1000); 
       } 
       catch(InterruptedException ie){} 
       if(s == 0) { 
        m--; 
        s=60; 
        if(m == -1) { 
         h--; 
         m=59; 
         tHrs.setText(Integer.toString(h)); 
        } 
        tMins.setText(Integer.toString(m)); 
       } 
       s--; 
       tSec.setText(Integer.toString(s)); 
      } 
     } 
     tHrs.setText("0"); 
     tMins.setText("0"); 
     tSec.setText("0"); 
    } 

    public void stopRunning() { 
     timeToQuit = true; 
    } 
} 

,我叫stopRunning()按下“停止”按钮时。它不会工作。

另外,我打电话给stopRunning()吗?

public void actionPerformed(ActionEvent ae) 
{ 
    Count cnt = new Count(); 
    Thread t1 = new Thread(cnt); 
    Object source = ae.getSource(); 
    if (source == bStart) 
    { 
     t1.start(); 
    } 
    else if (source == bStop) 
    { 
     cnt.stopRunning(); 
    } 
} 

回答

5

你需要让你的timeToQuit变量volatilefalse否则价值会被缓存。此外,没有理由让它Boolean - 原始将工作以及:

private volatile boolean timeToQuit=false; 

您还需要内环要注意的条件更改为timeToQuit

while(s>=0 && !timeToQuit) { 
    ... 
} 

你可以还要加上interrupt的电话,但由于您的线程永远不会超过检查该标志的秒数,所以这不是必需的。

+1

如何使用Thread.interrupt()? –

+0

@RahulTripathi是的,人们可以这样做,但由于OP的代码每秒都会检查一次标志,所有这些都可以为您节省时间。 – dasblinkenlight

+0

得到了......实际上我只是想知道在这里使用中断是否合适..谢谢! –