Volatile Flag Stops Worker Loop
A volatile flag gives the worker loop a fresh read of shared state every iteration, so a writer thread stops it promptly instead of never.
Code
public class ShutdownSwitch {
private static volatile boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread worker = Thread.ofPlatform().start(() -> {
int scanned = 0;
// volatile 保证每轮循环都重新读主内存里的 running,
// 而不是把值缓存进寄存器后永远看不到写线程的更新
while (running) {
scanned++;
}
System.out.println("worker stopped after " + scanned + " iterations");
});
Thread.sleep(50);
running = false; // volatile 写:对读线程立即可见
worker.join(1000);
System.out.println("worker alive: " + worker.isAlive());
}
}Inside the snippet
Volatile Flag Stops Worker Loop keeps everything in the class ShutdownSwitch.
Iteration happens inside while (running) — everything outside it runs once.
Putting it to use
Output lines are prefixed (worker stopped after, worker alive:), making each step’s effect easy to spot.
Core lines
Thread worker = Thread.ofPlatform().start(() -> {
int scanned = 0;
// volatile 保证每轮循环都重新读主内存里的 running,
// 而不是把值缓存进寄存器后永远看不到写线程的更新
while (running) {
scanned++;
}
System.out.println("worker stopped after " + scanned + " iterations");
});
Thread.sleep(50);
Interactive Tools for This Topic
FAQ
- What does Volatile Flag Stops Worker Loop print when run?
- Execute the whole file; each printed line is prefixed with a label like `worker stopped after`, `worker alive:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.