【发布时间】:2016-06-11 12:24:41
【问题描述】:
我最近和一个朋友就这样的代码发生了争执:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* See memory consistency effects in a Java Executor.
*/
public class PrivateFieldInEnclosing {
private long value;
PrivateFieldInEnclosing() {}
void execute() {
value = initializeValue();
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(new Y());
}
class Y implements Runnable {
@Override
public void run() {
System.out.println(value);
}
}
private long initializeValue() {
return 20;
}
public static void main(String[] args) {
new PrivateFieldInEnclosing().execute();
}
}
我认为value 有可能在Y 中被视为0,因为不能保证分配value = initializeValue() 在执行程序的线程中是可见的。我说他需要使value 成为一个易变字段。
他反驳了我,说因为它是私有实例字段,在创建线程之前分配了值,所以值是可见的。
我查看了https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4,但我无法确定我可以使用什么来支持我的声明。谁能帮我?谢谢!
【问题讨论】:
标签: java multithreading concurrency