Thread interruption is a way in which a thread who is either in sleeping or waiting state can be made to stop sleeping or waiting by throwing InterruptedException. If thread is not in sleeping or waiting state then calling thread interruption methods will not affect the program and programs will execute normally it just sets the interrupt flag to true.
Let’s see the methods provided by thread class for interrupting a thread.
Thread interruption mechanism depends on an internal flag called interrupt status. In below method will check what will be the effect on status flag when we call these methods.
public void interrupt(): In this method Initial value of this internal flag is false. After calling interrupt() method on the thread , value of internal flag is set to true. Note that InterruptedException will be thrown only when a thread is interrupted while in sleep or wait and then set the status to false.
public boolean isInterrupted(): this method will return the value of internal flag either true or false.
public static boolean interrupted():This method will check whether the current thread has been interrupted or not.It will return true if the current thread has been interrupted; otherwise false.Also, note that next call of interrupted would return false unless the current thread were interrupted again. Interrupted() is same as isInterrupted with the difference that , it clears interrupt status of a thread means if interrupt status is true, then it will set the status to false.
Example For Interrupting a thread :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.j2eereference; public class ThreadInterruptedDemo { public static void main(String args[]) { MyRunnable myRunnable = new MyRunnable(); Thread t = new Thread(myRunnable, "Thread-A"); t.start(); System.out.println("Thread interrupt status return by isInterrupted() before interrupting is :"+t.isInterrupted()); t.interrupt(); System.out.println("Thread interrupt status return by isInterrupted() after interrupting is :"+t.isInterrupted()); } } class MyRunnable implements Runnable { public void run() { try { for(int i = 0; i <= 10; i++) { System.out.println(Thread.currentThread().getName()+"is running"); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName() + " has been interrupted"); System.out.println("After throwing interrupted exception, interrupted() method will return interrupt status as : "+Thread.currentThread().interrupted()); } } } |
OutPut :
Thread interrupt status return by isInterrupted() before interrupting is :false
Thread-Ais running
Thread interrupt status return by isInterrupted() after interrupting is :true
Thread-A has been interrupted
Second call of interrupted() method will return interrupt status as : false