gpt4 book ai didi

java - 一条先于其他指令/语句的指令/语句是否保证首先执行?

转载 作者:搜寻专家 更新时间:2023-11-01 03:18:38 26 4
gpt4 key购买 nike

考虑取自 Joshua Bloch 的 Java Concurrency in Practice一书中的片段-

public class NoVisibility{
private static boolean ready;
private static int number;

private static class ReaderThread extends Thread{
public void run(){
while(!ready)
Thread.yield();
System.out.println(number);
}
}

public static void main(String[] args){
new ReaderThread().start();
number = 42; // Statement 1
ready = true; // Statement 2
}
}

对于JVM启动的ma​​in线程,是否保证statement 1会在statement 2之前执行。

我完全理解 ReaderThread 可能无法看到上述两个静态变量的更新值。我不是在寻求解决方案。但是,如果语句 1 在语句 2 之前执行,ReaderThread 是否仍然可以看到 ready 而不是 number 的更新值?这就是重新排序的一般含义吗?


同一本书页面底部的一段话揭示了对此的洞察-

There is no guarantee that operations in one thread will be performed in the order given by the program, as long as the reordering is not detectable from within that thread—even if the reordering is apparent to other threads.

这里有点困惑-

作者说...只要从该线程中检测不到重新排序...与此同时,他说-

——即使重新排序对其他线程来说是显而易见的(清晰可见)。

如果以防万一,其他线程可以清楚地看到重新排序,为什么他同时说 “只要从该线程内部检测不到重新排序”如果重新排序可见,则意味着它也可以检测到。不是吗?

最佳答案

一般情况下不能保证。也不能保证会发生更新,因为没有 volatile 被添加到其中一个字段。这将同步线程的缓存,并保证顺序。

(希望我是正确的。)


澄清(我希望)

给定的场景与 jvm 处理的 java 字节码无关。它(通常)并不是编译器巧妙地重新排列或无序解释字节码。它是在具有本地线程缓存的线程中运行的即时编译代码,重复保存公共(public)变量。

一个 volatile 标记字段确保那些公共(public)变量同步到所有线程。当然,只要结果没问题,单个线程可以按任何顺序执行代码。

y = ++x;

下面伪汇编的实际执行

1. move from @x to register1
2. increment register1
3. move from register1 to @x
4. move from register1 to @y
5. synchronize @x and @y

在不同的处理器上可能会完全不同。一个或两个变量可能缓存在线程内存本身中,或者需要写入 far 变量,或者不需要。

当然可以保证处理同一个线程给出正确的结果。并且没有人看到,顺序无关紧要:由于内存的原因,4 可能先于 3 或者比 3 快。

如果 3. 和 4. 被 JIT 编译切换,同一个线程将看不到/检测到任何差异,但其他线程可能首先看到 y 的变化。那是没有 volatile 的。

This all is quite esoteric, too low-level. One might wonder that it came in the language specification, just like that a byte variable is stored in a 4 byte word internally. It deals with implementation issues, that indeed are relevant, like missing byte operations. When one is interested in the topic, take an assembler, maybe combined with C and try these things out. Otherwise keep away from unsafe programing.

关于java - 一条先于其他指令/语句的指令/语句是否保证首先执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38694206/

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