Advertisement



< Prev
Next >



InterruptedException in Thread



Java provides us ways to interrupt an executing thread. We can interrupt a java thread by calling interrupt() method on it. On the call to interrupt() method, a java thread will automatically throw an exception of type InterruptedException in a couple of situations.









Interrupting a thread while during it is sleeping -:


In this code, we are trying to make a thread throw an InterruptedException by calling interrupt() method on it, during its sleep(after calling sleep() method on it).
class Intr implements Runnable	   	    //implementing the Runnable interface
{

public void run()  //Entry Point of the new thread.
{

try
{
	Thread.sleep(3000); //This will make the thread(Thread2) sleep for 3000ms.
	
}
catch(InterruptedException e)
{
	System.out.println("Thread is interrupted - " + e);
}			

}


public static void main(String... ar)
{
Intr newTh= new Intr();
Thread th= new Thread(newTh, "Thread2");    //Calling Thread's constructor & passing the object
					    //of class that  implemented  Runnable interface
					    //& the name of new thread.

//Starts the thread(Thread2)
th.start();		

//Main thread interrupting the thread(Thread2) while it is sleeping, causing InterruptedException
th.interrupt();		
}

}


Output is - :


Thread is interrupted - java.lang.InterruptedException: sleep interrupted


Program Analysis





Advertisement




Interrupting a thread while before it is sleeping -:


Now we are trying to make the main thread(default thread) throw an InterruptedException by calling interrupt() method on it, before it is going to sleep(by calling sleep() method).

class Intr 
{

public static void main(String... ar)
{	
//Accessing the reference of main thread, a default thread
Thread th = Thread.currentThread(); 

//Interrupting the main thread.
th.interrupt();

try
{
	Thread.sleep(3000);
}
catch(Exception e)
{
	System.out.println(e + " in "+ th.getName()); //Printing the name of main thread.
}

}
}


Output is :


java.lang.InterruptedException: sleep interrupted in main


Program Analysis






Please share this article -




< Prev
Next >
< Interrupt a running thread
Synchronization >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON


Advertisement