How to stop a thread in Java with Example
GIAN Tutorials
12:47 AM
It's easy to start a thread in Java because you have a start() method but it's difficult to stop the thread because there is no working stop() method. Well, there was a stop() method in Thread class, when Java was first released but that was deprecated later. In today's Java version, You can stop a thread by using a boolean volatile variable . If you remember, threads in Java start execution from run() method and stop, when it comes out of run() method, either normally or due to any exception. You can leverage this property to stop the thread. All you need to do is create a boolean variable e.g. Exit or Stop . Your thread should check its value every iteration and comes out of the loop and subsequently from run() method if Exit is true. In order to stop the thread, you need to set the value of this boolean variable to true when you want to stop a running thread. Since you are setting this variable from a different thread e.g. main thread, it's i