Java Reference
In-Depth Information
catch (InterruptedException ie)
{
}
thd.stopThread();
}
}
pableThread
thatsubclasses
Thread
.
StoppableThread
declaresa
stopped
fieldinitializedto
false
,a
stopThread()
methodthatsetsthisfieldto
true
,and
a
run()
methodwhoseinfiniteloopchecks
stopped
oneachloopiterationtoseeif
its value has changed to
true
.
After instantiating
StoppableThread
, the default main thread starts the thread
associated with this
Thread
object. It then sleeps for one second and calls
Stop-
pableThread
's
stop()
method before dying. When you run this application on a
single-processor/single-core machine, you will probably observe the application stop-
ping.
You might not see this stoppage when the application runs on a multiprocessor ma-
chine or a uniprocessor machine with multiple cores. For performance reasons, each
processor or core probably has its own cache with its own copy of
stopped
. When
one thread modifies its copy of this field, the other thread's copy of
stopped
is not
changed.
Listing4-25
refactors
Listing4-24
toguaranteethattheapplicationwillruncorrectly
on all kinds of machines.
Listing 4-25.
Guaranteed stoppage on a multiprocessor/multicore machine
class ThreadStopping
{
public static void main(String[] args)
{
class StoppableThread extends Thread
{
private boolean stopped = false;
@Override
public void run()
{