Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

java volatile 重排序的疑惑

有如下代码

public class VolatileSortTest {
    private static  int a = 0;
 private static  int b = 0;
 private static  int c = 0;
 private static  volatile int d = 0;
 private static  int e = 0;
 private static  int f = 0;
 private static  int g = 0;
 private static  int h = 0;
 public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 500000; i++) {
            //join可以保证线程a b都执行完成之后,再继续下一次循环
 ThreadA threadA = new ThreadA();
 ThreadB threadB = new ThreadB();
 threadA.start();
 threadB.start();
 threadA.join();
 threadB.join();
 //清空数据,便于测试
 a = 0;
 b = 0;
 c = 0;
 d = 0;
 e = 0;
 f = 0;
 g = 0;
 h = 0;
 }
    }
    static class ThreadA extends Thread {
        @Override
 public void run() {
            a = 1;
 b = 1;
 c = 1;
 d = 1;
 e = 1;
 f = 1;
 g = 1;
 h = 1;
 }
    }
    static class ThreadB extends Thread {
        @Override
 public void run() {
            if (b == 1 && a == 0) {
                System.out.println("b=1");
 }
            if (c == 1 && (a == 0 || b == 0)) {
                System.out.println("c=1");
 }
            if (d == 1 && (a == 0 || b == 0 || c == 0)) {
                System.out.println("d=1");
 }
            if (e == 1 && (a == 0 || b == 0 || c == 0 )) {
                System.out.println("e=1");
 }
            if (f == 1 && (a == 0 || b == 0 || c == 0 )) {
                System.out.println("f=1");
 }
            if (g == 1 && (a == 0 || b == 0 || c == 0 )) {
                System.out.println("g=1");
 }
            if (h == 1 && (a == 0 || b == 0 || c == 0 )) {
                System.out.println("h=1");
 }
        }
    }
}

我想要测试 volatile 关键词的禁止指令重排序,但是结果很出人意外,依然会打印出一些"g=1","f=1","e=1" 的字样,已经把d 添加了关键字 volatile,在操作d的时候会添加内存屏障,为什么 g = 1 的时候,a,b,c还有存在为0的现象?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

volatile 应该只能保证你看不到 "d=1" ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...