Friday, 27 December 2019

How to stop a thread in Java?


Approach 1: By Interrupting the thread
while (true) {
 try {
  TimeUnit.SECONDS.sleep(1);
  System.out.println(counter++);
 } catch (InterruptedException e) {
  System.out.println("Thread is interrupted");
  break;
 }
}

Find the below working application.


Task.java
package com.sample.app;

import java.util.concurrent.TimeUnit;

public class Task implements Runnable {

 @Override
 public void run() {
  int counter = 1;

  while (true) {
   try {
    TimeUnit.SECONDS.sleep(1);
    System.out.println(counter++);
   } catch (InterruptedException e) {
    System.out.println("Thread is interrupted");
    break;
   }
  }
  System.out.println("Exiting from thread");

 }

}


App.java
package com.sample.app;

import java.util.concurrent.TimeUnit;

public class App {

 public static void main(String args[]) throws InterruptedException {

  Thread t1 = new Thread(new Task());
  
  t1.start();
  
  TimeUnit.SECONDS.sleep(5);
  
  t1.interrupt();
  t1.join();
  System.out.println("Exiting Application");

 }
}


Run App.java, you will get below messages in console.
1
2
3
4
Thread is interrupted
Exiting from thread
Exiting Application

Approach 2: Using a flag


Task.java
package com.sample.app;

import java.util.concurrent.TimeUnit;

public class Task implements Runnable {

 private boolean running = true;

 public void terminate() {
  System.out.println("Instruction received to stop the thread");
  running = false;
 }

 @Override
 public void run() {
  int counter = 1;

  while (running) {
   try {
    TimeUnit.SECONDS.sleep(1);
    System.out.println(counter++);
   } catch (InterruptedException e) {
    System.out.println("Thread is interrupted");
    break;
   }
  }
  System.out.println("Exiting from thread");

 }

}


App.java
package com.sample.app;

import java.util.concurrent.TimeUnit;

public class App {

 public static void main(String args[]) throws InterruptedException {

  Task task = new Task();
  Thread t1 = new Thread(task);

  t1.start();

  TimeUnit.SECONDS.sleep(5);

  task.terminate();
  t1.join();
  System.out.println("Exiting Application");

 }
}

Run App.java, you can see below kind of messages in console.

1
2
3
4
Instruction received to stop the thread
5
Exiting from thread
Exiting Application

Note

In case if the same task object is shared by multiple threads, define flag using volatile modifier.


You may like

No comments:

Post a Comment