Java Reference
In-Depth Information
while(!isStopped())
System.out.println("running");
}
synchronized void stopThread()
{
stopped = true;
}
private synchronized boolean isStopped()
{
return stopped;
}
}
StoppableThread thd = new StoppableThread();
thd.start();
try
{
Thread.sleep(1000); // sleep for 1 second
}
catch (InterruptedException ie)
{
}
thd.stopThread();
}
}
support thread communication (between the default main thread that calls
stopThread()
and the started thread that executes inside
run()
). When a thread
enters one of these methods, it is guaranteed to access a single shared copy of the
stopped
field (not a cached copy).
Synchronization is necessary to support mutual exclusion or mutual exclusion com-
bined with thread communication. However, there is an alternative to synchronization
whentheonlypurposeistocommunicatebetweenthreads.Thisalternativeisreserved
Listing 4-26.
The
volatile
alternative to synchronization for thread communication