Java Reference
In-Depth Information
minates the loop. This causes the
run()
method to return, ending the thread. The
ThreadStoppers
program in the source directory for this chapter has a main program that
instantiates and starts this class and then calls the
shutDown()
method.
Example 22-7. StopBoolean.java
public
public class
class
StopBoolean
StopBoolean
extends
extends
Thread
{
// MUST be volatile to ensure changes visible to other threads.
protected
protected volatile
volatile
boolean
boolean
done
=
false
false
;
public
public
void
void
run
() {
while
while
(!
done
) {
System
.
out
.
println
(
"StopBoolean running"
);
try
try
{
sleep
(
720
);
}
catch
catch
(
InterruptedException ex
) {
// nothing to do
}
}
System
.
out
.
println
(
"StopBoolean finished."
);
}
public
public
void
void
shutDown
() {
done
=
true
true
;
}
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
InterruptedException
{
StopBoolean t1
=
new
new
StopBoolean
();
t1
.
start
();
Thread
.
sleep
(
1000
*
5
);
t1
.
shutDown
();
}
}
Running it looks like this:
StopBoolean running
StopBoolean running
StopBoolean running
StopBoolean running
StopBoolean running
StopBoolean running
StopBoolean running
StopBoolean finished.