when I uncomment the block of code below (which is currently commented out), the program never stops. I do not understand why?
Note the javadoc of Thread#interrupt()
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.
So if you uncomment your code, the flag gets lifted and your if
never executes.
Does Thread Class maintains a static list of all the Threads that is currently running and by calling Thread.currentThread()
The Thread.currentThread()
method is declared as (Oracle JDK 7)
public static native Thread currentThread();
In other words, it is natively implemented, probably in C code. We can assume, given the javadoc, that, somewhere, a reference to all threads is stored. The currently executing one is returned.
Similarly, the Thread#isInterrupted()
method calls
private native boolean isInterrupted(boolean ClearInterrupted);
which is also natively implemented. But we can assume it uses some boolean-style flag.