Java Reference
In-Depth Information
Compliant Solution (Volatile Flag)
Thiscompliantsolutiondeclarestheflagfield
volatile
toensurethatupdatestoitsvalue
are made visible across multiple threads:
final class ControlledStop implements Runnable {
private volatile boolean done = false;
@Override public void run() {
//...
}
// ...
}
The
volatile
keyword establishes a happens-before relationship between this thread
and any other thread that sets
done
.
Compliant Solution (
Thread.interrupt()
)
Abettersolutionformethodsthatcall
sleep()
istousethreadinterruption, whichcauses
the sleeping thread to wake immediately and handle the interruption.
final class ControlledStop implements Runnable {
@Override public void run() {
// Record current thread so others can interrupt it
myThread = currentThread();
while (!Thread.interrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public void shutdown(Thread th) {
th.interrupt();