Java重新排序会影响System.currentTimeMillis()吗? [英] Does Java reordering affect System.currentTimeMillis()?

查看:167
本文介绍了Java重新排序会影响System.currentTimeMillis()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Java内存模型,只要执行格式良好

According to Java Memory Model, instructions can be reordered as long as the execution is well-formed.

所以我想知道,以下代码是否可能产生以下输出?

So I wonder, is it possible that the following codes produces the following output?

[代码] [在同一个帖子中]

long a = System.currentTimeMillis();
long b = System.currentTimeMillis();
long c = System.currentTimeMillis();

[输出]

a == 10, b == 20, c == 15

如果不可能,那么JVM /实现会做些什么来防止这种情况发生?

If not possible, then what does JVM / implementations do to prevent this from happening?

推荐答案

请参阅这个问题指令重新排序&发生在java之前的关系

我相信除非你在一个不同的线程中,否则任何执行的结果总是与顺序一致你的代码。在这种情况下,由于无法按顺序处理它,即使你的字段对另一个线程可见,它也应该是好的。

I believe that unless you are in a different thread, the outcome of any execution will always be consistent with the order in your code. In this situation, since it is impossible to process it out of order, it should be good even if your fields are visible to another thread.

这篇关于Java重新排序会影响System.currentTimeMillis()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆