When a Thread is first created, it has never been interrupted, so calling isInterrupted() will return false. If the Thread goes along its merry way and is never interrupted, then calling isInterrupted() will never return true. Ok, this was the easy part.
When you want to interrupt a thread, you need to have a reference to it, ie, a variable that holds a reference to the thread you want to interrupt. Say I have a variable myThread of type Thread, that contains a reference to the thread I want to interrupt. I can now interrupt that thread by calling
myThread.interrupt();
What does this do to the called thread? Like I mentioned above, this sets the internal interrupted flag for the thread. Now if I have code in the myThread Thread that calls isInterrupted(), it will return true.
Now, it starts getting a little more tricky. If myThread is running a loop and not explicitly calling sleep() or wait(), then it must check for the interrupted status by polling the isInterrupted() method continuously. For example:
- while(true) { //endless loop
- //do a lot of stuff
- if (isInterrupted()){
- //deal with the interrupt in any way we want
- }
- //do more stuff
- }
If we don't check the isInterrupted() result, then we will never know if we were interrupted or not. Also, note the interrupt mechanism is a tool for you to use to design your software-what you actually do after being interrupted is up to your algorithm and specific to your program. It's just a way for one Thread to tap another Thread on the shoulder and say "excuse me Mr. Thread..."; after that it's up to you do something with that interruption.
Now, the other method, interrupted() is similar to isInterrupted() in that it returns the true/false status of the interrupted flag, EXCEPT it also clears the flag, so if you call interrupted() and it returns true, the very next time you call interrupted() it will return false, untill your thread is again interrupted. This method is useful when you are going to be interrupted a lot and you want to make sure you only handle each interruption one time, with a specific method for example.
Finally, there are 2 methods that are special when dealing with interrupts, namely wait() and sleep(). If a Thread is blocked, either because it is sleeping, or waiting, then it's not actively running, and so it can't actively respond to an interrupt from another thread. So the designers of java provided a mechanism whereby if you interrupt a Thread that is asleep, or waiting for a lock, it can be "woken up" to handle the interruption. That's why you must wrap calls to sleep() or wait() in a try/catch block and catch the InterruptedException.
Hope this helps.