I was playing around with following example:
public static void interrupted() throws InterruptedException {
Runnable task = () -> {
while(true && !Thread.currentThread().isInterrupted()) {
System.out.println("task executing");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread thread = new Thread(task);
thread.start();
//lets allow spawned thread to run by sleeping main thread for 10 seconds
Thread.currentThread().sleep(10000);
thread.interrupt();
}
when I run this method I was expecting :
1 that the task started via Runnable would run a few times and print SOP
2 above would be possible since main thread sleeps for 10 seconds
3 once main thread wakes up it calls interrupt on the spawned thread
4 in the Runnable task we are checking for isInterrupted so this should get triggered and spawned thread should exit thereby allowing the JVM to exit.
However this is not happening and eclipse / jvm shows that the spawned thread is still running the while loop
Here is the console :
task executing
task executing
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at basics.StopEx.lambda$1(StopEx.java:39)
at java.lang.Thread.run(Thread.java:748)
task executing
task executing
task executing
task executing
........
The java docs regarding interrupt do seem to indicate that calling 'sleep' would cause a different behavior ( highlighted below ) - can someone throw some light on what is exactly happening here and why ?
Interrupts this thread.
Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
If this thread is blocked in an I/O operation upon an InterruptibleChannel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a java.nio.channels.ClosedByInterruptException.
If this thread is blocked in a java.nio.channels.Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
If none of the previous conditions hold then this thread's interrupt status will be set.
Interrupting a thread that is not alive need not have any effect.