【发布时间】:2014-08-02 19:19:02
【问题描述】:
我有一个关于 Java 中发生前发生机制的问题。示例如下:
public class MyThread extends Thread {
int a = 0;
volatile int b = 0;
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
read();
}
public void write(int a, int b) {
this.a = a;
this.b = b;
}
public void read() {
System.out.println(a + " " + b);
}
}
据我所知,这是happens-before 的明显示例,而且足够安全。 a 将正确获得新值,因为它位于 b 的初始化之前。但重新订购是否意味着安全得不到保障?我说的是这个:
public void write(int a, int b) {
this.b = b;
this.a = a;//might not work? isn't it?
}
UPD主线程:
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.write(1, 2);
}
}
【问题讨论】:
-
能否添加包含 start() 调用的代码?我无法准确理解你在这里问什么
标签: java multithreading volatile java-memory-model