Pin It

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 : 
 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot