I have a thread that runs in a loop, and would like to kill a thread once a dialog that started the thread closes. What is the best way to do that?
Asked
Active
Viewed 344 times
1
-
What type of dialog? What context? Please do tell the details necessary for us to give an intelligent answer. – Hovercraft Full Of Eels Nov 20 '12 at 03:03
2 Answers
5
You can call interrupt()
for the thread. This won't stop the thread, however, unless you do something about it inside the thread loop.
Thread t = new Thread() {
@Override
public void run() {
while (shouldLoop() && !isInterrupted()) {
. . .
}
}
}();
// somewhere else:
t.interrupt(); // will exit thread on next loop iteration
If you don't want to use interrupt()
(say, you don't have a reference to the thread), you can set a flag somewhere that is accessible to the thread code. You still need to check it in the thread loop and exit the loop (and the run()
method) to exit the thread.

Ted Hopp
- 232,168
- 48
- 399
- 521
-
@RyanNaddy - You have to write the loop in such a way that it frequently checks `isInterrupted()` (or whatever flag you use) and exits the loop when the flag becomes set. – Ted Hopp Nov 20 '12 at 04:16
-
I did it just like the example and it seems to exit the loop correctly. `while(true && !this.isInterrupted()){` is what I am using. – Get Off My Lawn Nov 20 '12 at 13:49