Wednesday 24 August 2016

How to Stop Thread in Java?

By default, a Thread stops when execution of run() method finish either normally or due to any Exception.
It is tricky to stop the Thread execution in Java as stop() method has been deprecated from Thread Class.

To make the thread stop, we organise for the run() method to exit.

Stop using boolean State variable or flag:
It is very popular to stop a Thread using flag and it's also safe because it doesn't do anything special rather than helping run() method to finish itself.
class Runner extends Thread {
     private boolean exit = false;

     @Override
     public void run() {
           while(!exit) {
                System.out.println("Thread is running");
                try {
                     Thread.sleep(500);
                } catch (InterruptedException ex) {
                     System.out.println("Exception !!");
                }
           }
           System.out.println("Stopped !!");
     }
     public void exit(boolean bExit) {
           this.exit = bExit;
     }
}

public class ThreadStopFlag {
     public static void main (String[] args) throws InterruptedException {
           Runner runner = new Runner();
           runner.start();
           Thread.sleep(1000);
           runner.exit(true);
     }
}

Output:
Thread is running
Thread is running
Stopped !!

Stop using interrupt() method:
class Runner1 extends Thread {
     @Override
     public void run() {
           while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Thread is running");
           }
           System.out.println("Stopped !!");
     }
}

public class ThreadStopUsingInterrupt {
     public static void main (String[] args) throws InterruptedException {
           Runner1 runner = new Runner1();
           runner.start();
          
           Thread.sleep(1);
          
           runner.interrupt();
     }
}
Output:
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Thread is running
Stopped !!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...