Java Interrupting Thread


If you are calling the interrupt() method which breaks the sleeping or waiting state thread throws interrupted Exception. when you calling the interrupt() method without using sleep and wait, which flow the normal program.


Methods:

The following three methods which make interrupting a thread.

  • public void interrupt()
  • public static boolean interrupted()
  • public boolean isInterrupted()

Example:

The normal thread flow stops working when the thread is interrupting.

class InterDemo extends Thread{  
    public void run(){  
        try{  
            Thread.sleep(1000);  
            System.out.println("task");  
        }catch(InterruptedException e){  
            System.out.println(e);
        }  
    }  
    public static void main(String args[]){  
        InterDemo t1=new InterDemo();  
        t1.start();  
        try{  
            t1.interrupt();  
        }catch(Exception e){
            System.out.println("Exception handled "+e);
        }  
      
    }  
} 

Example:

The normal thread flow does not stop working even the thread is interrupted.

class InterDemo1 extends Thread{  
    public void run(){  
        try{  
            Thread.sleep(500);  
            System.out.println("task");  
        }catch(InterruptedException e){  
            System.out.println(e);
        }  
        System.out.println("thread is still running...");  
    }  
    public static void main(String args[]){  
        InterDemo1 t1=new InterDemo1();  
        t1.start();  
        t1.interrupt();
      
    }  
}   



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.