Search This Blog

Monday, 18 August 2014

How to Interrupt Thread - JAVA

How to Interrupt Thread in Java

When you run a secondary thread, it will run to completion or till an exception occurs or you explicitly interrupted from the process that created it.


This program shows how to Interrupt Thread in Java..

InterruptThreadJava.java

public class InterruptThreadJava {
 public static void main(String args[]){
  MyThread thread = new MyThread();
  thread.start();
  //stop thread after 2 iterations
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  thread.interrupt();
  System.out.println("Iterrupt called");
 }
}

MyThread.java

public class MyThread extends Thread {
 @Override
 public void run() {
  int iterator = 5;
  try {
   for (int i = 0; i < iterator; i++){
    System.out.println("From 2nd Thread:  i = " + i);
    sleep(1000);
   }
  } catch (InterruptedException e) {
   System.out.println("Thread interrupted");
  }
 }
}

No comments:

Post a Comment