java in 语句保证排序_java – 是否保证在other / s之前的指令/语句首先被执行?...

考虑一下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启动的主线程,是否保证语句1将在语句2之前执行.

我完全理解ReaderThread可能无法看到上述两个静态变量的更新值.我不是要求解决方案.但是如果语句1在语句2之前执行,那么ReaderThread是否仍然可以看到ready&的更新值.不是为了号码?这是重新排序的意思吗?

同一本书页面底部的一个段落揭示了对此的见解 –

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字节码那么重要. (通常)不是这样编译器巧妙地重新排列或解释字节代码.它是在具有本地线程缓存的线程中运行的即时编译代码,重复地保存公共变量.

volatile标记字段可确保将这些公共变量同步到所有线程.当然,只要结果合适,单个线程就可以以任何顺序执行代码.

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的变化.那是没有动荡的.

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

来源: https://codeday.me/bug/20190702/1353383.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值