小编lma*_*uts的帖子

发生在Java内存模型中的规则之前

我目前正在攻读并发编程考试并且不明白为什么这个程序的输出是43.为什么x = y + 1之前执行t.start()?我还应该解释在我使用的规则之前发生了什么.

如果我理解程序顺序规则(一个线程中的每个动作发生 - 在该程序顺序后面的那个线程中的每个动作之前)t.start()都必须在执行之前执行,x = y + 1以便线程t复制变量x1.

public class HappensBefore {

static int x = 0;
static int y = 42;

public static void main(String[] args) {
    x = 1;
    Thread t = new Thread() {
        public void run() {
            y = x;
            System.out.println(y);
        };
    };
    t.start();
    x = y + 1;
}
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading java-memory-model happens-before

5
推荐指数
2
解决办法
395
查看次数