Originally posted by Narasimha Rao B.:
Can i use the interrupt() method to interrupt normal working threads or only for sleeping and waiting threads.
...
At // 1, i am interrupting the thread, 'th', but there is no effect.
Yes, you can interrupt a thread that is not already blocked in some way. However, how it responds to that interruption is a little different.
If you look at the API Spec for
API Spec for Thread, you'll find this under the description of the interrupt method:
If none of the previous conditions hold then this thread's interrupt status will be set.
That's saying that, if the thread is not blocking for some reason and received an interruption, it will set a status (basically sets a boolean variable to true). It's now up to the thread to check to see if it has been interrupted or not. I modified your
test program a little to look like this:
I pulled this excerpt from the output:
As you can see, the main thread is sending an interruption to the spawned thread and the spawned thread can react to that interruption by utilizing the interrupted() method defined within Thread.
Note that you can also use isInterrupted() to determine if the thread has received an interrupt (as opposed to interrupted). However, interrupted() will reset the interrupted status to false while isInterrupted will leave it unchanged. You can look at the full descriptions of both within the API Spec.
I hope that helps,
Corey