JaVa
   

Interrupting a Thread

There is a common misconception about the interrupting of threads, as you plot InterruptedException try/catch blocks everywhere, that you might throw interrupts everywhere thinking, "Oh, I hope an exception doesn't get randomly thrown here from Java or something, fingers crossed." This in fact isn't the case; the interrupts are there as a system for you to utilize when handling your threads. Throughout many examples in this chapter, we have seen the requirement to try/catch InterruptedException exceptions that could be thrown. Interrupting a thread is useful for immediate action when a thread is blocking or to simply give it a status that it can then make a check to during its execution. There are two main aspects of interrupting a thread that you need to be aware of: interrupting the thread that is in a blocked status or in a non-blocked status. You should be aware of blocking by now. This simply means, in terms of a thread with a stopped execution, like when we call wait on an object or sleep a thread, it blocks. You'll note that in these circumstances we try/catch an InterruptedException exception. That is how we handle an interrupt when a thread is blocked. In order to interrupt a thread, you can call the interrupt method of a thread object.

Thread myThread = new Thread(myRunnableObject);
myThread.start();
// interrupt the thread myThread.interrupt();


When we interrupt a thread that is blocked (e.g., if it's calling sleep or waiting on an object to be notified), the thread will resume and be thrown an InterruptedException, so you can handle the thread being interrupted in the catch block for this exception.

try
{
 myThread.sleep();
}
catch(InterruptedException e)
{
 // handle if blocking sleep method is interrupted
}


If the thread is in a running status, an interrupted status associated with the thread is set; just see it as a Boolean value, which it probably is. This value can be tested using one of two distinct methods: interrupted and isInterrupted. Both methods will return a Boolean value of the thread's interrupt status, but the interrupt method resets the status to false if it was true, whereas the isInterrupted method merely checks the status without affecting the value. An interesting thing about all this is that a thread can interrupt itself, setting the interrupt status for it to then handle later. The following code snippet will count from 10 to 0 and then stop using thread interrupting:

for(int i=10; !Thread.currentThread().interrupted(); i--)
{
 System.out.println(i);
 if(i==0)
 Thread.currentThread().interrupt();
}


Many programmers use the thread interrupt system to stop their threads from looping and allow them to exit, instead of the ways we discussed earlier in this chapter. It's basically your own preference.

JaVa
   
Comments