Java Reference
In-Depth Information
But what if your thread is blocked reading from a network connection? You then cannot
check a Boolean, because the thread that is reading is asleep. This is what the
stop
method
was designed for, but, as we've seen, it is now deprecated. Instead, you can simply close the
socket. The program shown in
Example 22-8
intentionally deadlocks itself by reading from a
socket that you are supposed to write to, simply to demonstrate that closing the socket does
in fact terminate the loop.
Example 22-8. StopClose.java
public
public class
class
StopClose
StopClose
extends
extends
Thread
{
protected
protected
Socket io
;
public
public
void
void
run
() {
try
try
{
io
=
new
new
Socket
(
"java.sun.com"
,
80
);
// HTTP
BufferedReader is
=
new
new
BufferedReader
(
new
InputStreamReader
(
io
.
getInputStream
()));
System
.
out
.
println
(
"StopClose reading"
);
new
// The following line will deadlock (intentionally), since HTTP
// enjoins the client to send a request (like "GET / HTTP/1.0")
// and a null line, before reading the response.
String line
=
is
.
readLine
();
// DEADLOCK
// Should only get out of the readLine if an interrupt
// is thrown, as a result of closing the socket.
// So we shouldn't get here, ever:
System
.
out
.
printf
(
"StopClose FINISHED after reading %s!?"
,
line
);
}
catch
catch
(
IOException ex
) {
System
.
out
.
println
(
"StopClose terminating: "
+
ex
);
}
}
public
public
void
void
shutDown
()
throws
throws
IOException
{
iif
(
io
!=
null
null
) {
// This is supposed to interrupt the waiting read.
synchronized
synchronized
(
io
) {
io
.
close
();
}
}
System
.
out
.
println
(
"StopClose.shutDown() completed"
);
}