从CSDN的某N篇博客上看到,当执行synchronized代码块时,会经历一下几个步骤:1 获得同步锁
2 清空工作内存
3 从主存拷贝变量副本到工作内存
4 对这些变量计算
5 将变量从工作内存写回到主存
6 释放锁
但是如果这么说的话我就有疑问了
class test{
public static void main(String[] args) {
test2 test2 = new test2();
//此时a可能并没有从本地副本中刷新到主内存
test2.a = 5;
synchronized (test.class) {
//清空工作空间的值,也就是把a清除
//从内存中重新读取a的值,a应该为0啊,为什么是5?
System.out.println(test2.a);
}
System.out.println(test2.a);
}
}
class test2{
public int a = 0;
}