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
currentThread(). interrupt() , you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.
interrupted() is static and checks the current thread. isInterrupted() is an instance method which checks the Thread object that it is called on.
currentThread. Returns a reference to the currently executing thread object.
currentThread() returns a reference to the thread that is currently executing. In the above example, I've used thread's getName() method to print the name of the current thread. Every thread has a name. you can create a thread with a custom name using Thread(String name) constructor.
In your case it is sufficient to just call !isInterrupted()
because you're extending from the Thread
class. Typically you don't extend from Thread
- that's why you call Thread.currentThread()
.
Starting from Java 5 it is not a good idea to work with Threads directly . You should rather use Executor framework and choose an execution policy depending on your requirements . The instance isInterrupted()
method tests whether this thread has been interrupted. The interrupted status of the thread is unaffected by this method.The inner isInterrupted()
is actually a native method .
906 public boolean isInterrupted() {
907 return isInterrupted(false);
908 }
While using the executor framework you do not know which thread instance is executing your code currently and hence the convention is to use Thread.currentThread.isInterrupted()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With