End Thread Execution
1) Using Boolean flag:
In this method, we declare one boolean variable called flag in a thread. Initially we set this flag as true. Keep the task to be performed in while loop inside the run() method by passing this flag. This will make thread continue to run until flag becomes false. We have defined stopRunning() method. This method will set the flag as false and stops the thread. Whenever you want to stop the thread, just call this method. Also notice that we have declared flag as volatile. This will make thread to read its value from the main memory, thus making sure that thread always gets its updated value.
2) By calling interrupt() method
In this method, we use interrupt() method to stop a thread. Whenever you call interrupt() method on a thread, it sets the interrupted status of a thread. This status can be obtained by interrupted() method. This status is used in a while loop to stop a thread.
Last updated