If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked),calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException.
Interrupt the thread which is in sleeping or waiting state - Exception
class TestInterrupt extends Thread {
public voidrun() {
try{
System.out.println("Thread sleep for 1 sec");
Thread.sleep(1000);
} catch(InterruptedException e) {
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]) {
TestInterrupt test = new TestInterrupt();
test.start();
try {
System.out.println("Call interrupt");
test.interrupt();
} catch(Exception e) {
System.out.println("Exception handled "+e);
}
}
}
Output:
Call interrupt
Thread sleep for1 sec
Exception in thread "Thread-0" java.lang.RuntimeException:
Thread interrupted...java.lang.InterruptedException: sleep interrupted
at TestInterrupt.run(TestInterrupt.java:10)
If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn't interrupt the thread but sets the interrupt flag to true.
Interrupt the thread which is not in sleeping or waiting state – No Exception
class TestInterrupt extends Thread {
public voidrun() {
System.out.println("Inside the run method");
int sum = 0;
for(inti=0;i<2000;i++) {
sum = sum + i;
}
System.out.println(sum);
}
public static void main(String args[]) {
TestInterrupt test = newTestInterrupt();
test.start();
try {
System.out.println("Call interrupt");
test.interrupt();
} catch(Exception e) {
System.out.println("Exception handled "+e);
}
}
}
Output:
Call interrupt
Inside the run method
1999000
Interrupting a thread that start working
After interrupting the thread, the thread will keep working after handling the InterruptedException.
If we will propagate the exception, the thread will stop working.
class TestInterrupt extends Thread {
public voidrun() {
try {
System.out.println("Thread in sleep state");
Thread.sleep(1000);
} catch(InterruptedException e) {
// if we propagate the exception - thread will stop working
//throw new RuntimeException("Thread interrupted..." +e);
}
System.out.println("Thread is running after interrupting");
}
public static void main(String args[]) {
TestInterrupt test = newTestInterrupt();
test.start();
try {
System.out.println("interrupting thread...");
test.interrupt();
} catch(Exception e) {
System.out.println("Exception handled "+e);
}
}
}
Output:
interrupting thread...
Thread in sleep state
Thread is running after interrupting
No comments:
Post a Comment