根据这个链接,我读到JVM通过将共享变量的数据从主内存复制到线程的工作内存来实现同步。
比如有这样一个类
class Test {
private Test2 test2 = new Test2();
public void print1() {}
public synchronized void print2() {
test2.print();
}
如果这个Test类在多个线程中执行,而“print2”方法在一个线程中执行,我认为Test上的锁被一个Thread获取,其他线程必须等待直到锁被释放。
现在我有一个问题。如果一个Thread 获得了Test 上的锁,是否意味着Test 和Test2 的数据从主内存复制到线程的工作内存?我之所以这么说是因为在实例方法级别使用了“synchronized”关键字,而 test2 是 Test 类的实例变量。
我只是想弄清楚什么是从主内存复制到线程的工作内存。
如有错误请指正
最佳答案
简而言之,当您使用 synchronized 时,所有共享变量都将被复制(即从缓存写入主内存,以便所有线程具有相同的数据)。当您使用 volatile 时,保证只会复制一个 volatile 变量。
我发现这是一个有用的资源,涉及到该主题。
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html
编辑:关于您的评论,specification 的第 17.6 节回答你的问题:
Let T be any thread, let V be any variable, and let L be any lock. There are certain constraints on the actions performed by T with respect to V and L:
Between a lock action by T on L and a subsequent use or store action by T on a variable V, an assign or load action on V must intervene; moreover, if it is a load action, then the read action corresponding to that load must follow the lock action, as seen by main memory. (Less formally: a lock action acts as if it flushes all variables from the thread's working memory; before use they must be assigned or loaded from main memory.)
关于内存模型的java同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8245742/