Java中的易失性变量在第二个线程上不可见吗?

问题描述 投票:0回答:1

我有一个带有两个线程AB的小示例应用程序。两者都花费一些CPU周期,然后才分别在一个易失性变量上设置一个值(A设置x的值,B设置y的值),然后B还打印出两个变量。当该游戏重复多次后,有时x的值在B中可见,但有时不可见(即使xy都是易失的)。为什么会这样?

public class Vol2 {

    public static volatile int x = 0;
    public static volatile int y = 0;

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 50; i++) {

            x = 0;
            y = 0;


            Thread t1 = new Thread(() -> {
                doWork();
                x = 5;
            });

            Thread t2 = new Thread(() -> {
                doWork();
                y = 6;
                System.out.println("x: " + x + ", y: " + y);
            });

            t1.start();
            t2.start();
            t1.join();
            t2.join();

        }
    }

    public static void doWork() {
        int s = 0;
        for (int i = 0; i < 1_000_000; i++) {
            s += i;
        }
    }
}
java java-memory-model
1个回答
0
投票

线程t1t2可以同时执行。无法保证在t1分配x并读取t2之前,y将分配x

© www.soinside.com 2019 - 2024. All rights reserved.