Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Various way to stop a thread - which is the correct way

I had came across different suggestion of stopping a thread. May I know, which is the correct way? Or it depends?

Using Thread Variable http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html

private volatile Thread blinker;

public void stop() {
    blinker = null;
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (blinker == thisThread) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}

Using boolean flag

private volatile boolean flag;

public void stop() {
    flag = false;
}

public void run() {
    while (flag) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}

Using Thread Variable together with interrupt

private volatile Thread blinker;

public void stop() {
    blinker.interrupt();
    blinker = null;
}

public void run() {
    Thread thisThread = Thread.currentThread();
    while (!thisThread.isInterrupted() && blinker == thisThread) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}
like image 800
Cheok Yan Cheng Avatar asked Feb 25 '23 09:02

Cheok Yan Cheng


2 Answers

None of these is the "correct" way, they're all valid. Which one you use depends on your circumstances, and which one works best for you.

As long as you don't use Thread.stop(), and you tidy up any resources left open by your threads (connections, temp files, etc), then it doesn't really matter how you go about it.

like image 187
skaffman Avatar answered Mar 05 '23 21:03

skaffman


I always use the boolean flag - its the simplest. Its really short and easy to understand for reviewers, but it has the handycap that you can't interrupt the sleep call. You should only use the interrupt variants for time-critical thread stopping. And, like skaffman said - Don't use Thread.stop()!

like image 23
Sibbo Avatar answered Mar 05 '23 22:03

Sibbo