An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. This is the usage emphasized in this lesson.A thread sends an interupt by invoking
interrupton theThreadobject for the thread to be interrupted. For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.Supporting Interruption
How does a thread support its own interruption? This depends on what it's currently doing. If the thread is frequently invoking methods that throwInterruptedException, it simply returns from therunmethod after it catches that exception. For example, suppose the central message loop in theSleepMessagesexample were in therunmethod of a thread'sRunnableobject. Then it might be modified as follows to support interrupts:Many methods that throwfor (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds try { Thread.sleep(4000); } catch (InterruptedException e) { //We've been interrupted: no more messages. return; } //Print a message System.out.println(importantInfo[i]); }InterruptedException, such assleep, are designed to cancel their current operation and return immediately when an interrupt is received.What if a thread goes a long time without invoking a method that throws
InterruptedException? Then it must periodically invokeThread.interrupted, which returnstrueif an interrupt has been received. For example:In this simple example, the code simply tests for the interrupt and exits the thread if one has been received. In more complex applications, it might make more sense to throw anfor (int i = 0; i < inputs.length; i++) { heavyCrunch(inputs[i]); if (Thread.interrupted()) { //We've been interrupted: no more crunching. return; } }InterruptedException:This allows interrupt handling code to be centralized in aif (Thread.interrupted()) { throw new InterruptedException(); }catchclause.The Interrupt Status Flag
The interrupt mechanism is implemented using an internal flag known as the interrupt status. InvokingThread.interruptsets this flag. When a thread checks for an interrupt by invoking the static methodThread.interrupted, interrupt status is cleared. The non-staticThread.isInterrupted, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.By convention, any method that exits by throwing an
InterruptedExceptionclears interrupt status when it does so. However, it's always possible that interrupt status will immediately be set again, by another thread invokinginterrupt.