synchronized void stopThread()
stopped = true;
private synchronized boolean isStopped()
StoppableThread thd = new StoppableThread();
Thread.sleep(1000); // sleep for 1 second
catch (InterruptedException ie)
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
word volatile , which Listing 4-26 demonstrates.
Listing 4-26. The volatile alternative to synchronization for thread communication