If you’ve been looking for an easy way to stop a thread running in your Java application, you’re in luck. Whether your thread is running or just long-waiting, there are a number of different ways to do this. You can use the Interrupted() method, or a boolean volatile variable.
Interrupt method
Java’s Interrupt method allows you to end a thread’s execution without blocking it. This method is useful for killing running threads, but it is difficult to wire throughout a program. The reason for this is that you need to know the thread’s current location to use this method.
Using a boolean volatile variable to stop a thread
You can use a boolean volatile variable to halt a thread by using the switch operator. For example, if a thread is running a game, you could use the switch operator to stop the game. But this is not a very good idea. This can lead to memory consistency errors.
Using a boolean volatile constant to stop a thread in Java will prevent compilation errors, and you can avoid the synchronization problem by not using the synchronize keyword in your code since volatile variables do not cache their values locally. When a thread checks the value of a volatile boolean variable, it will exit the thread if the value is true. To do this, you have to set the variable to true. You can do this from the main thread. This will prevent the thread from reusing the value and running indefinitely.
package com.theprogramguide; public class BooleanVolatileStop extends Thread { protected boolean stop = false; public void run( ) { while (!stop) { System.out.println("BooleanVolatileStop running"); try { sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } shutDown(); } System.out.println("BooleanVolatileStop finished."); } public void shutDown( ) { stop = true; } public static void main(String[ ] args) throws InterruptedException{ BooleanVolatileStop thread = new BooleanVolatileStop( ); thread.start(); } }