Java Reference
In-Depth Information
throwsee Chapter 20 for more details on I/O). Even if the interruption
cannot be responded to during the I/O operation, systems may check
for interruption at the start of the operation and throw the exception-
hence the need for an interrupted thread to clear its interrupted state if
it needs to perform I/O as part of its cleanup. In general, however, you
cannot assume that interrupt will unblock a thread that is performing
I/O.
Every method of every class executes in some thread, but the behavior
defined by those methods generally concerns the state of the object in-
volved, not the state of the thread executing the method. Given that,
how do you write methods that will allow threads to respond to in-
terrupts and be cancellable? If your method can block, then it should
respond to interruption as just discussed. Otherwise, you must de-
cide what interruption or cancellation would mean for your method and
then make that behavior part of the methods contractin the majority of
cases methods need not concern themselves with interruption at all. The
golden rule, however, is to never hide an interrupt by clearing it expli-
citly or by catching an InterruptedException and continuing normallythat
prevents any thread from being cancellable when executing your code.
The interruption mechanism is a tool that cooperating code can use to
make multithreading effective. Neither it, nor any other mechanism, can
deal with hostile or malicious code.
14.8.2. Waiting for a Thread to Complete
One thread can wait for another thread to terminate by using one of the
join methods. The simple form waits forever for a particular thread to
complete:
class CalcThread extends Thread {
private double result;
public void run() {
result = calculate();
}
 
Search WWH ::




Custom Search