I have a question regarding the implementation of a cancellation policy for a Thread subclass. It seems to be common practice to do it like this:
class A extends Thread {
[...]
public final void run() {
try {
while(!Thread.currentThread().isInterrupted()) {
[...]
}
} catch (InterruptedException consumed) {
}
}
public final void cancel() {
interrupt();
}
}
The question I have is regarding Thread.currentThread()… Why is it common practice to use currentThread() for checking the interruption flag but not for setting it in the cancel() method? Wouldn’t it suffice to just call the isInterrupted() method of A like this:
while (!isInterrupted()) {
[...]
}
I couldn’t find an answer neither in the Thread JavaDoc, Brian Goetz’ excellent book on concurrent Java or stackoverflow.
Thanks in advance for your insights!
Cheers,
Georg
In your case it is sufficient to just call
!isInterrupted()because you’re extending from theThreadclass. Typically you don’t extend fromThread– that’s why you callThread.currentThread().