Java Reference
In-Depth Information
Ending main()
Marilyn Monroe java.lang.InterruptedException: sleep interrupted
Slim Pickens java.lang.InterruptedException: sleep interrupted
Hopalong Cassidy java.lang.InterruptedException: sleep interrupted
How It Works
Because the
main()
method calls the
interrupt()
method for each of the threads after you press the
Enter key, the
sleep()
method that is called in each thread registers the fact that the thread has been in-
terrupted and throws an
InterruptedException
. This is caught by the
catch
block in the
run()
method
and produces the new output that you see. Because the
catch
block is outside the
while
loop, the
run()
method for each thread returns and each thread terminates.
You can check whether a thread has been interrupted by calling the
isInterrupted()
method for the
thread. This returns
true
if
interrupt()
has been called for the thread in question. Because this is an
instance method, you can use this in one thread to determine whether another thread has been interrup-
ted. For example, in
main()
you could write:
if(first.isInterrupted()) {
System.out.println("First thread has been interrupted.");
}
Note that this determines only whether the interrupted flag has been set by a call to
interrupt()
for
the thread — it does not determine whether the thread is still running. A thread could have its interrupt
flag set and continue executing — it is not obliged to terminate because
interrupt()
is called. To test
whether a thread is still operating, you can call its
isAlive()
method. This returns
true
if the thread has
not terminated.
The instance method
isInterrupted()
in the
Thread
class has no effect on the interrupt flag in the
thread — if it was set, it remains set. However, the static
interrupted()
method in the
Thread
class is
different. It tests whether the currently executing thread has been interrupted, and if it has, it clears the
interrupted flag in the current
Thread
object and returns
true
.
When an
InterruptedException
is thrown, the flag that registers the interrupt in the thread is cleared,
so a subsequent call to
isInterrupted()
or
interrupted()
returns
false
.
Connecting Threads
If in one thread you need to wait until another thread dies, you can call the
join()
method for the thread that
you expect isn't long for this world. Calling the
join()
method with no arguments halts the current thread
for as long as it takes the specified thread to die:
thread1.join(); // Suspend the current thread until thread1 dies
You can also pass a
long
value to the
join()
method to specify the number of milliseconds you're pre-
pared to wait for the death of a thread:
thread1.join(1000); // Wait up to 1 second for thread1 to die