Java Reference
In-Depth Information
< Day Day Up >
Puzzle 84: Rudely Interrupted
In this program, a thread tries to interrupt itself and then checks whether it succeeded. What does
the program print?
public class SelfInterruption {
public static void main(String[] args) {
Thread.currentThread().interrupt();
if (Thread.interrupted()) {
System.out.println("Interrupted: " +
Thread.interrupted());
} else {
System.out.println("Not interrupted: " +
Thread.interrupted());
}
}
}
Solution 84: Rudely Interrupted
Although it is not common for a thread to interrupt itself, it isn't unheard of, either. When a method
catches an InterruptedException and is not prepared to deal with it, the method usually rethrows
the exception. Because it is a checked exception, a method can rethrow it only if the method
declaration permits. If not, the method can "reraise" the exception without rethrowing it, by
interrupting the current thread. This works fine, so our program should have no trouble interrupting
itself. Therefore, the program should take the first branch of the if statement and print
Interrupted: true . If you ran the program, you found that it doesn't. It doesn't print Not
interrupted: false , either; it prints Interrupted: false .
It looks as if the program can't make up its mind about whether the thread was interrupted. Of
 
 
Search WWH ::




Custom Search