Java Reference
In-Depth Information
Hopalong Pickens
Slim Cassidy
Hopalong Monroe
Marilyn
Enter pressed...
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
Since the method
main()
calls the
interrupt()
method for each of the threads after you press the
Enter
key, the
sleep()
method called in each thread registers the fact that the thread has been
interrupted and throws an
InterruptedException
. This is caught by the
catch
block in the
run()
method and produces the new output 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. Since this is an
instance method, you can use this to determine in one thread whether another thread has been
interrupted. For example, in
main()
you could write:
if(first.isInterrupted())
System.out.println("First thread has been interrupted.");
Note that this only determines 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()
has no effect on the interrupt flag in the thread - if it was set,
it remains set. However, the static method
interrupted()
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()
will return
false
.
Connecting Threads
If you need to wait in one thread 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 will halt
the current thread for as long as it takes the specified thread to die:
thread1.join(); // Suspend the current thread until thread1 dies