1

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?

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

2 Answers2

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
0

You could listen to the dialogs close event, and interrupt the thread.

Community
  • 1
  • 1
totymedli
  • 29,531
  • 22
  • 131
  • 165