Use boolean value to stop a thread in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 19-Feb-2019 11:05:30
Advertisements