Wednesday, 2 May 2012

INTERRUPTS IN THREAD




                                                   INTERRUPTS IN THREAD




Interrupts are just the mechanism to wake thread from a sleep of a waiting stage . Apart from that it doesn't do anything else . Basically , it's a flag internal to thread , which can be used to check whether this thread has been interrupted or not.


But if you catch interrupt exception , as in case of Thread sleep or waiting for a object , this flag is automatically reset by the JVM . Lets check out a simple program






When you run this piece of dirty code the , the output is :





As you could see when I try to interrupt the child Threads in sleep and wait state respectively, InterruptedException is thrown , but when you try to check Thread.currentThread().isInterrupted() , this ends up in false , because JVM automatically resets the flag after the exception is caught.


Now if we make a small tweak to the run method in the above code





If you see the code here , Thread is trying to interrupt itself , so the output comes out to be




As we could see here  Thread.currentThread().isInterrupted() gives value 'true' , as we havent caught the exception.

No comments:

Post a Comment