stringbacon
stringbacon

Reputation: 33

How can I stop a thread?

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.

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

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

Upvotes: 3

Views: 113

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

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:

private volatile boolean timeToQuit=false;

You also need to change the condition of the inner loop to pay attention to 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.

Upvotes: 5

Related Questions