Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to interrupt a thread in Java ?




Program to demonstrate how to interrupt a thread in Java


package com.hubberspot.multithreading;

public class InterruptedThread {

 public static void main(String[] args) {
  // 3. Create a thread by instantiating
  // an object from the class
  Thread count = new Counter();

  // 4. Call the start() method of the 
  // thread object
  count.start();

  for(int i = 0; i < 100; i++) {
   // loops through till i == 5
   // interrupts the Counter class thread at 
   // i==5 
   if(i == 5){
    try {
     Thread.sleep(5000);
    } catch (InterruptedException e) {

     e.printStackTrace();
    }
   }
   if(i == 5){
    // Calling interrupt method on 
    // count object
    count.interrupt();
   }
  }

 }

}


class Counter extends Thread {

 public void run(){

  int i = 0;
  // Till the thread is not interrupted 
  // it loops and prints count 
  while(!isInterrupted()){

   System.out.println("Count is " + i++);
   try {
    // Have a pause so that 
    // as soon as interruption occur 
    // it throws InterruptedException and 
    // thread of Counter class gets interrupted
    Thread.sleep(1000);

   } catch (InterruptedException e) {

    break;
   }
  }
  System.out.println("Thread Interrupted");
 }

}

Output of the program : 
 
 
© 2021 Learn Java by Examples Template by Hubberspot