I have created class by implementing runnable interface and then created many threads(nearly 10) in some other class of my project.
How to stop some of those threads?
The simplest way is to interrupt()
it, which will cause Thread.currentThread().isInterrupted()
to return true
, and may also throw an InterruptedException
under certain circumstances where the Thread is waiting, for example Thread.sleep()
, otherThread.join()
, object.wait()
etc.
Inside the run()
method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted()
value and do something (for example, break out).
Note: Although Thread.interrupted()
seems the same as isInterrupted()
, it has a nasty side effect: Calling interrupted()
clears the interrupted
flag, whereas calling isInterrupted()
does not.
Other non-interrupting methods involve the use of "stop" (volatile
) flags that the running Thread monitors.