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(); } }
Quickly Find What You Are Looking For
Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.