What is the Thread.interrupt()method’s purpose?

What is the Thread.interrupt()method’s purpose?

What is the purpose of the Thread.interrupt()method? I expect that if I call the interrupt()method of a sleeping thread, anInterruptedException will be thrown. Here is aquick code sample showing my thoughts (pleaseforgive the formatting):

*/   class Timer extends Thread {      public void run() {               for(int i = 0; i 
I expect that when is called, Iwill see output resembling
What am I missing?

I compiled and ran this code, and no message appeared. Thecurious behavior you’re experiencing can probably be attributed to the fact thatlike an Error, an InterruptedException isasynchronous. In otherwords, the InterruptedException is thrown at a slightlydifferent pointduring the execution of _timer each time it runs.

Asynchronous exceptions aren’t handled the same way as otherexceptions. The Java virtual machine must periodically check tosee if any asynchronous exceptions have been raised. This is usuallydone by special instructions inserted into your code by thecompiler. Naturally, this raises code optimization issues. Somecompilers only insert checks for asynchronous exceptions aftera “transfer of control.” This may mean a function call or acontext switch. It might even be the case that some compilers havean optimization option that doesn’t insert any checks for theseexceptions.


Share the Post: