gpt4 book ai didi

java并发实践16.1

转载 作者:行者123 更新时间:2023-11-30 09:32:57 25 4
gpt4 key购买 nike

在这段代码中:

public class PossibleReordering {
static int x = 0, y = 0;
static int a = 0, b = 0;

public static void main(String[] args)
throws InterruptedException {
Thread one = new Thread(new Runnable() {
public void run() {
a = 1;
x = b;
}
});
Thread other = new Thread(new Runnable() {
public void run() {
b = 1;
y = a;
}
});
one.start(); other.start();
one.join(); other.join();
System.out.println("( "+ x + "," + y + ")");
}
}

他们说 Java 编译器会重新排序线程一和线程另一中的指令以优化其执行,最终导致结果 (0,0)。

他们还说:
线程中的每个操作都发生在该线程中程序顺序中稍后出现的每个操作之前。

这两个说法是否相互冲突?

最佳答案

happens-before 规则只适用于相互依赖的语句。由于这些 run() 方法都包含独立的赋值,因此允许编译器对它们重新排序,这可能会导致您描述的输出。
您可以在 Javaspecs here 中阅读 happens-before 的定义。 :

It should be noted that the presence of a happens-before relationship between two actions does not necessarily imply that they have to take place in that order in an implementation. If the reordering produces results consistent with a legal execution, it is not illegal.

例如,如果第一个 run() 方法如下所示:

public void run() {
b = 1;
x = b;
}

不允许重新排序。

关于java并发实践16.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12418337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com