【发布时间】:2019-03-09 21:18:06
【问题描述】:
我需要一些帮助。 我正在尝试创建一个示例,显示需要 volatile 来防止指令重新排序。
在这个例子中,我试图证明 b > a 只有在发生重新排序并且 volatile 会阻止它时。
问题是每次运行我都会得到 b>a,我一定是错过了一些愚蠢的东西,但我看不到它。
我在这里错过了什么?
public class Example04Reorder extends Thread {
volatile static int a = 0;
volatile static int b = 0;
public static void main(String[] args) throws InterruptedException {
Example04Reorder t = new Example04Reorder();
t.start();
while( true )
{
if ( b > a ) // supposedly happens only on reordering
{
System.out.println("b was bigger than a");
System.exit(1);
}
}
}
public void run() {
while (true)
{
a = 5;
b = 4;
b = 0;
a = 0;
}
}
}
【问题讨论】:
-
Re,“我正在尝试创建一个显示需要 volatile 的示例。”仅供参考,如果您不遵守规则,则永远不能保证多线程程序表现不佳。 Java 语言规范只是允许它表现不佳。这就是编写正确的多线程程序如此困难的原因之一:您无法仅通过测试来证明程序是正确的。
标签: java multithreading synchronization