Search code examples
javavolatile

I expect infinite loop,but not,why?


code like this

for test two case

one is have volatile keywords ,can stop

other is without volatile,the thread infinite loop

public class VolatileTest extends Thread {

    public boolean flag = false;

    public static void main(String[] args) throws InterruptedException {
        VolatileTest volatileTest = new VolatileTest();
        volatileTest.start();
        Thread.sleep(1000);
        volatileTest.flag = true;
    }

    @Override
    public void run() {
        while (!flag) {
            System.out.println("=====>");
        }
    }
}

enter image description here


Solution

  • My mistake. The problem is that you are calling a synchronized method inside your while loop. Try it like this. Stopped will never print unless you redeclare flag as volatile.

    public class VolatileTest extends Thread {
    
        public boolean flag = false;
    
        public static void main(String[] args) throws InterruptedException {
            VolatileTest volatileTest = new VolatileTest();
            volatileTest.start();
            Thread.sleep(1000);
            volatileTest.flag = true;
            System.out.println("flag is now " + flag);
             
        }
    
        @Override
        public void run() {
            int i = 0;
            while (!flag) {
                i++;
            }
            System.out.println("stopped");
        }
    }