我是全栈架构师 2017-09-05 06:25 采纳率: 0%
浏览 753
已结题

关于java的volatile问题

这段代码为什么会输出a:1,b:3呢, 我加了volatile关键字,不是一个线程修改了值,对另一个线程可见吗 ?

 public class Test4 {

    //加了volatile,为什么会出现: a:1,b:3

    volatile long a = 1;
    volatile long b = 2;


    public void change(){
        a = 3;
        b = a;
    }

    public void print(){
        System.out.println("a:"+a+",b:"+b);
    }

    public static void main(String[] args) {
        while (true){
            final Test4 test4 = new Test4();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        Thread.sleep(10);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    test4.change();
                }
            }).start();


            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        Thread.sleep(10);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    test4.print();
                }
            }).start();

        }
    }
}
  • 写回答

3条回答 默认 最新

  • threenewbee 2017-09-05 07:00
    关注

    volatile 只能保证单个变量的修改是原子的
    a = 3;
    b = a;
    这样分两行写,还是需要同步的。

    评论

报告相同问题?