我期望无限循环,但不是,为什么

voj3qocg  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(469)

像这样的代码
测试二的情况
一是有易变关键字,可以停止
另一种是无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;
    }

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

uyto3xhc

uyto3xhc1#

我的错。问题是你打电话给 synchronized while循环中的方法。像这样试试。 Stopped 除非你重新申报否则不会打印 flag 作为 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");
    }
}

相关问题