How to stop a thread created by implementing runnable interface?
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.
How to stop a thread created by implementing runnable interface?
There are many ways that you can stop a thread but all of them take specific code to do so. A typical way to stop a thread is to have a volatile boolean shutdown
field that the thread checks every so often:
// set this to true to stop the thread volatile boolean shutdown = false; ... public void run() { while (!shutdown) { // continue processing } }
You can also interrupt the thread which causes sleep()
, wait()
, and some other methods to throw InterruptedException
. You also should test for the thread interrupt flag with something like:
public void run() { while (!Thread.currentThread().isInterrupted()) { // continue processing try { Thread.sleep(1000); } catch (InterruptedException e) { // good practice Thread.currentThread().interrupt(); return; } } }
Note that that interrupting a thread with interrupt()
will not necessarily cause it to throw an exception immediately. Only if you are in a method that is interruptible will the InterruptedException
be thrown.
If you want to add a shutdown()
method to your class which implements Runnable
, you should define your own class like:
public class MyRunnable implements Runnable { private volatile boolean shutdown; public void run() { while (!shutdown) { ... } } public void shutdown() { shutdown = true; }}
Stopping the thread in midway using Thread.stop()
is not a good practice. More appropriate way is to make the thread return programmatically. Let the Runnable object use a shared variable in the run()
method. Whenever you want the thread to stop, use that variable as a flag.
EDIT: Sample code
class MyThread implements Runnable{ private Boolean stop = false; public void run(){ while(!stop){ //some business logic } } public Boolean getStop() { return stop; } public void setStop(Boolean stop) { this.stop = stop; } }public class TestStop { public static void main(String[] args){ MyThread myThread = new MyThread(); Thread th = new Thread(myThread); th.start(); //Some logic goes there to decide whether to //stop the thread or not. //This will compell the thread to stop myThread.setStop(true); }}