美文网首页
System.out.println()对于内存可见性的影响

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

作者: ssssssnake | 来源:发表于2018-10-23 00:36 被阅读0次

    群友发了一段代码,说变量没有加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

    相关文章

      网友评论

          本文标题:System.out.println()对于内存可见性的影响

          本文链接:https://www.haomeiwen.com/subject/cjtozftx.html