简体   繁体   中英

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("=====>");
        }
    }
}

在此处输入图像描述

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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM