. .
Implementing enableInterrupts()
Thus far we've been dealing with these issues by writing snippets of ad hoc code--sufficient to the
immediate problem but not easily reused. In Code Example 9-18 we show a subclass of Thread
that deals with these problems more neatly. Because the methods are synchronized, there are no
race conditions. If a thread has not disabled interrupts, interrupt() will call the method for the
superclass [the normal interrupt()]. That interrupt will remain pending until either the
programmer's code clears it [via calling interrupted() or catching
InterruptedException] or disableInterrupts() is called.[10] If
disableInterrupts() gets called, the flag will be cleared and our interruptPending flag
will be set. This ensures that a subsequent call to enableInterrupts() will reinterrupt the
thread so that the interruption does not get lost.
These are static methods (as it only makes sense to call them from the current thread), but they
must be called from an InterruptibleThread. You will get a runtime error otherwise.
Example 9-18 Implementing enableInterrupts()
public class InterruptibleThread extends Thread {
private boolean interruptsEnabled = false;
private boolean interruptPending = false;
public static void enableInterrupts() {
InterruptibleThread self =
synchronized (self) {
self.interruptsEnabled = true;
if (self.interruptPending)
self.interruptPending = false;
public static void disableInterrupts() {
InterruptibleThread self =
synchronized (self) {
if (interrupted())
self.interruptPending = true;
self.interruptsEnabled = false;
public synchronized void interrupt() {
if (interruptsEnabled)
interruptPending = true;
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks