I think, it is the job of the interrupt() method. Interruption is a mechanism whereby a thread that is waiting (or sleeping) can be made to prematurely stop waiting. I'm not sure about that execution of all sleep() method will be interrupted!
Let's see, what other do!
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
See java docs where it is clearly given
"If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException".
Yea. But, one doubt : is interrupt() method comes to action, when every time that particular thread goes to sleep/blocked mode? Please clear my doubt. Here, the Thread t1 goes to sleep every time the method cube is being invoked on the Thread and it doesn't stay in that sleep state. is this because of interrupt() method called on that thread?
Thanks in Advanced!
Joined: Jul 18, 2008
yes it is coming in action everytime it is going to sleep mode.
The t1 output never pauses per second, and never gets the random interrupt, and it always completes the 20 iterations.
The t2 thread pauses per second, and gets the "random reset".
Can anyone explain the behaviour please?
BTW, different platforms have different Thread Schedulers, which give different results. I executed the Sleep_Interrupt code on a Mac OS X with JRE 6 and did not get the t2 thread pause per second and did not get the "random resets".
Abimaran Kugathasan wrote:Yea. But, one doubt : is interrupt() method comes to action, when every time that particular thread goes to sleep/blocked mode? Please clear my doubt. Here, the Thread t1 goes to sleep every time the method cube is being invoked on the Thread and it doesn't stay in that sleep state. is this because of interrupt() method called on that thread?
Call to interrupt() sets 'interrupted' flag of the thread.
Then when sleep() is called, this flag is checked and if this flag is true, sleep() aborts immediately with InterruptedException and this flag is cleared.
Your code catch this exception, and in the catch block this flag is set to true again, so next invocation of sleep() will throw InterruptedException again.
Joined: May 18, 2009
Thank you Larry, its interesting to see how very different the result is on a Mac.
Thank you Ireneusz, that appears to be the case. I have added a little more output to prove the point:
(on WinXP) for every iteration of t1 it gives the output
For every iteration of t2 "line 22" is read:
This appears to mean that the execution of main processes the interrupt before the t1.start goes into run()?