Use boolean value to stop a thread in Java


A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called.

A thread can be stopped using a boolean value in Java. The thread runs while the boolean value stop is false and it stops running when the boolean value stop becomes true.

A program that demonstrates this is given as follows:

Example

class ThreadDemo extends Thread {
   public boolean stop = false;
   int i = 1;
   public void run() {
      while (!stop) {
         try {
            sleep(10000);
         } catch (InterruptedException e) {
         }
         System.out.println(i);
         i++;
      }
   }
}
public class Demo {
   public static void main(String[] args) {
      ThreadDemo t = new ThreadDemo();
      t.start();
      try {
         Thread.sleep(10000);
      } catch (InterruptedException e) {
      }
      t.stop = true;
      System.out.println("The thread is stopped");
   }
}

Output

1
2
3
4
5
The thread is stopped

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 30-Jul-2019

678 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements