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();
}
}
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.
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()
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With