我怎么能停止一个线程?

时间:2021-05-19 02:11:55

I made a countdown timer and a "Stop" button is suppose to stop the countdown and reset the textfields.

我做了一个倒计时器,一个“停止”按钮假设停止倒计时并重置文本字段。

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;
    }
}

and I call stopRunning() when the "Stop" button is pressed. It won't work.

当按下“停止”按钮时,我调用stopRunning()。它不会起作用。

also, am i calling the stopRunning() right??

另外,我正在调用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();
    }
}

1 个解决方案

#1


5  

You need to make your timeToQuit variable volatile, otherwise the value of false will be cached. Also, there's no reason to make it Boolean - a primitive would work as well:

您需要使timeToQuit变量易变,否则将缓存false的值。此外,没有理由将其设为布尔值 - 原语也可以使用:

private volatile boolean timeToQuit=false;

You also need to change the condition of the inner loop to pay attention to timeToQuit:

你还需要改变内循环的条件来注意timeToQuit:

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

You could also add a call to interrupt, but since your thread is never more than a second away from checking the flag, this is not necessary.

你也可以添加一个中断调用,但由于你的线程永远不会超过检查标志一秒钟,这是没有必要的。

#1


5  

You need to make your timeToQuit variable volatile, otherwise the value of false will be cached. Also, there's no reason to make it Boolean - a primitive would work as well:

您需要使timeToQuit变量易变,否则将缓存false的值。此外,没有理由将其设为布尔值 - 原语也可以使用:

private volatile boolean timeToQuit=false;

You also need to change the condition of the inner loop to pay attention to timeToQuit:

你还需要改变内循环的条件来注意timeToQuit:

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

You could also add a call to interrupt, but since your thread is never more than a second away from checking the flag, this is not necessary.

你也可以添加一个中断调用,但由于你的线程永远不会超过检查标志一秒钟,这是没有必要的。

相关文章