Java Reference
In-Depth Information
public
public static
static void
void main ( String [] args )
throws
throws InterruptedException , IOException {
StopClose t = new
new StopClose ();
t . start ();
Thread . sleep ( 1000 * 5 );
t . shutDown ();
}
}
When run, it prints a message that the close is happening:
StopClose reading
StopClose terminating: java.net.SocketException: Resource temporarily unavailable
“But wait,” you say. “What if I want to break the wait, but not really terminate the socket?”
A good question, indeed, and there is no perfect answer. But you can interrupt the thread that
is reading; the read is interrupted by a java.io.InterruptedIOException , and you can
retry the read. The file Intr.java in this chapter's source code shows this.
Rendezvous and Timeouts
Problem
You need to know whether something finished or whether it finished in a certain length of
time.
Solution
Start that “something” in its own thread and call its join() method with or without a timeout
value.
Discussion
The join() method of the target thread is used to suspend the current thread until the target
thread is finished (returns from its run() method). This method is overloaded; a version with
no arguments waits forever for the thread to terminate, whereas a version with arguments
waits up to the specified time. For a simple example, I create (and start!) a simple thread that
Search WWH ::




Custom Search