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();
}
}
Listing 4-25 ' s stopThread() and isStopped() methods are synchronized to
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
word volatile , which Listing 4-26 demonstrates.
Listing 4-26. The volatile alternative to synchronization for thread communication
Search WWH ::




Custom Search