Java Reference
In-Depth Information
class ThreadStopping
{
public static void main(String[] args)
{
class StoppableThread extends Thread
{
private volatile boolean stopped = false;
@Override
public void run()
{
while(!stopped)
System.out.println("running");
}
void stopThread()
{
stopped = true;
}
}
StoppableThread thd = new StoppableThread();
thd.start();
try
{
Thread.sleep(1000); // sleep for 1 second
}
catch (InterruptedException ie)
{
}
thd.stopThread();
}
}
Listing4-26 declares stopped tobe volatile ;threadsthataccessthisfieldwill
alwaysaccessasinglesharedcopy(notcachedcopiesonmultiprocessor/multicorema-
chines). As well as generating code that is less verbose, volatile might offer im-
proved performance over synchronization.
Search WWH ::




Custom Search