8

How to kill a running thread in java

JavaUser
  • 25,542
  • 46
  • 113
  • 139

3 Answers3

12

You can ask the thread to interrupt, by calling Thread.interrupt()

Note that a few other methods with similar semantics exist - stop() and destroy() - but they are deprecated, because they are unsafe. Don't be tempted to use them.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    . destroy() is not depricated. – JavaUser Jun 28 '10 at 07:36
  • 1
    See Bozho's "unsafe" link, in particular the "What should I use instead of Thread.stop()" section, to see the canonical way to actuall *kill* a thread. Interrupt will merely cause any currently-executing blocking calls to stop running, but will not in itself stop the thread from executing. – Andrzej Doyle Jun 28 '10 at 07:37
  • 2
    @JavaUser it is, as of Java 1.5 – Bozho Jun 28 '10 at 07:40
  • 2
    @JavaUser - there is also the "slight problem" that the javadoc prior to JDK 1.5 for `destroy()` says *"(This method is not implemented.)"*. It won't work even if you try to use it. – Stephen C Jun 28 '10 at 07:44
6

As Bozho said, Thread.interrupt() is the generic and right way to do it. But remember that it requires the thread to cooperate; It is very easy to implement a thread that ignores interruption requests.

In order for a piece of code to be interruptible this way, it shouldn't ignore any InterruptedException, and it should check the interruption flag on each loop iteration (using Thread.currentThread().isInterrupted()). Also, it shouldn't have any non-interruptible blocking operations. If such operations exist (e.g. waiting on a socket), then you'll need a more specific interruption implementation (e.g. closing the socket).

Eyal Schneider
  • 22,166
  • 5
  • 47
  • 78
2

Shortly you need Thread.interrupt()

For more details check the section How do I stop a thread that waits for long periods (e.g., for input) in this article Why Are Thread.stop, Thread.suspend,Thread.resume and Runtime.runFinalizersOnExit Deprecated?.

reevesy
  • 3,452
  • 1
  • 26
  • 23
Incognito
  • 16,567
  • 9
  • 52
  • 74