"Hello, Amigo! You have to admit that Ellie's Cancel idea was brilliant."
"Actually, something similar exists in the Thread class. Only the variable isn't called isCancel. It's called isInterrupt. And the method used to stop the thread isn't cancel(). It's interrupt()."
"Yes. Check it out:"
|Because several threads can call the run method on the same Clock object, we get the Thread object for the current thread.
The Clock class writes the word "Tick" to the console once a second as long as the current thread's isInterrupt variable is false.
When isInterrupt becomes true, the run method terminates.
|The main thread starts a child thread (clock) that should run forever.
Wait 10 seconds and cancel the task by calling the interrupt method.
The main thread completes its work.
The clock thread ends its work.
Moreover, the sleep method, which people are so fond of using in endless loops in the run method, automatically checks the isInterrupt variable. If a thread calls the sleep method, the method first checks whether isInterrupt is true for that thread. If it is true, the method won't sleep. Instead, it throws an InterruptedException exception.
"Why throw an exception? Wouldn't it be better to simply put isInterrupted() instead of isCancel() in a loop?"
"First, the run method doesn't always have a loop. The method might simply consist of a few dozen calls to other methods. Then you would have to add an isInterrupted check before each method call."
"Second, some method that involves lots of different actions might take a very long time to execute."
"Third, throwing an exception doesn't replace the isInterrupted check. It's just a convenient addition. The thrown exception lets you to quickly unwind the call stack back to the run method itself."
"Fourth, the sleep method is used a lot. As it turns out, this helpful method is enhanced by an implicit check that is no less helpful. It's as if nobody specifically added the check, but there it is. This is super valuable when you're using someone else's code and you can't add the check yourself."
"Fifth, the additional check doesn't degrade performance. Calling the sleep method means that the thread shouldn't be doing anything (except sleeping), so the extra work doesn't bother anyone."
"Those are serious arguments."
"And, finally, there's this: Your run method can call someone else's code—code that you don't have access to (source code and/or rights to change the code). It might not have isInterrupted checks, and it might use "try ... catch (Exception e)" to catch all exceptions."
Nobody can guarantee that a thread will be stopped. Only a thread can stop itself.
GO TO FULL VERSION