JavaUser
JavaUser

Reputation: 26334

killing a running thread in java?

How to kill a running thread in java

Upvotes: 8

Views: 13200

Answers (3)

Incognito
Incognito

Reputation: 16577

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?.

Upvotes: 2

Eyal Schneider
Eyal Schneider

Reputation: 22446

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).

Upvotes: 6

Bozho
Bozho

Reputation: 597106

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.

Upvotes: 12

Related Questions