并发问题使 volitile 无法工作

a concurrency problem makes volitile not work

B线程读取两个全局变量,A线程写入两个全局变量。

second怎么可能比first大很多?

public class ThreadTest {
    private static volatile int first = 0;
    private static volatile int second = 0;

    private static class ReaderThread extends Thread {
        @Override
        public void run() {
            while (first < 10000) {
                if (first != second) {
                    System.out.println("ThreadB------first = " + first + ", second = " + second);
                }
            }
            System.out.println("ThreadB------first = " + first + ", second = " + second);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ReaderThread().start();
        Thread.sleep(1000L);
        while (first < 10000){
            first++;
            second++;
        }
    }
}
ThreadB------first = 3296, second = 3535
ThreadB------first = 7615, second = 7663
ThreadB------first = 8179, second = 8192
ThreadB------first = 8635, second = 8662
ThreadB------first = 9151, second = 9177
ThreadB------first = 10000, second = 10000
ThreadB------first = 10000, second = 10000

发生了什么事,如何解决这个问题?

满足'if'后,执行一些比较慢的-运行字符串连接。在读取 'first' 和读取 'second' 期间,从左到右评估 println 调用的参数表达式时,可能会经过一些未知的时间长度(可能是数百个机器周期)。

尝试重新编码为

   int f = first, s = second;
   if (f != s) {
        System.out.println("ThreadB------first = " + f + ", second = " + s);
   }

然后看看它是什么样子。

更大的问题是,如果这是一些真实代码的片段,它似乎无法提供任何有用的同步。每个整数都有立即可见的效果,但两个值之间没有同步。我能看到的唯一保证是,如所写,您永远不会看到 'second' 的值小于 'first'.

的值