©布鲁斯·埃克尔(Bruce Eckel)“论Java 8”

我一定有误解,因为此代码无法像这样工作

public class Reordering {
    private int x;
    private volatile int y;

    public void writer() {
        x = 1;
        y = 2;
    }

    public void reader() {
        if (y == 2) {
            if(x == 0) {
                // X assignment is happens-before for
                // volatile Y assignment
                // so X can't be 0 when Y equals 2
                throw new RuntimeException();
            }

            x = 0;
            y = 0;
        }
    }

    public static void main(String[] args) {
        Reordering reordering = new Reordering();

        Thread thread = new Thread(() -> {
            while (true) {
                reordering.writer();
            }
        });

        thread.setDaemon(true);
        thread.start();

        while (true) {
            reordering.reader();
        }
    }
}

最佳答案

我认为,当编写者只是设置了x=1,而阅读器已经位于if块中时(在变量赋值之前),就会出现此问题:

reader             writer state
-----------------  ------ --------
stops before x=0          x=1, y=2
                   x=1    x=1, y=2
x=0                       x=0, y=2
y=0                       x=0, y=0
                   y=2    x=0, y=2
reader will throw

09-05 09:05