public class VolatileExample { // Declare a volatile variable private volatile boolean flag = true; public void changeFlag() { // This method is called by one thread to change the value of the flag this.flag = false; System.out.println("Flag has been set to false."); } public void runLoop() { // This method is called by another thread which keeps running until the flag becomes false System.out.println("Waiting for flag to become false."); while (flag) { // Busy wait - the loop will keep running as long as flag is true } System.out.println("Flag is now false, stopping the loop."); } public static void main(String[] args) throws InterruptedException { VolatileExample example = new VolatileExample(); // Thread for running the loop Thread loopThread = new Thread(example::runLoop); // Thread for changing the flag Thread changeFlagThread = new Thread(example::changeFlag); loopThread.start(); Thread.sleep(1000); // Wait for 1 second before changing the flag changeFlagThread.start(); } }