System.out.println()对于内存可见性的影响

群友发了一段代码,说变量没有加volatile,但是依旧可见,代码大致如下:
public class StopThreadTest implements Runnable {

private boolean flag = true;

public static void main(String[] args) throws InterruptedException {

    StopThreadTest stopThreadTest = new StopThreadTest();
    Thread thread = new Thread(stopThreadTest);
    thread.start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    stopThreadTest.flag = false;
}

@Override
public void run() {
    int i = 0;
    while (flag) {
        System.out.println(i);
    }
    System.out.println("计数器已经停止");
}

}

这段代码甚至差点让我改变三观。。。

经过若干测试后,发现问题出在System.out.println(i); 这个方法包含一个加锁的动作,如下:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容