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?
I have created class by implementing runnable interface and then created many threads(nearly 10)
Share
The simplest way is to
interrupt()it, which will causeThread.currentThread().isInterrupted()to returntrue, and may also throw anInterruptedExceptionunder certain circumstances where the Thread is waiting, for exampleThread.sleep(),otherThread.join(),object.wait()etc.Inside the
run()method you would need catch that exception and/or regularly check theThread.currentThread().isInterrupted()value and do something (for example, break out).Note: Although
Thread.interrupted()seems the same asisInterrupted(), it has a nasty side effect: Callinginterrupted()clears theinterruptedflag, whereas callingisInterrupted()does not.Other non-interrupting methods involve the use of “stop” (
volatile) flags that the running Thread monitors.