读取和写入单个变量是原子的(语言保证!),除非变量的类型为long或double.
我正在读一个课程的幻灯片,我发现写了.这个类是关于并发的.
任何人都可以向我解释为什么写长或双不是原子操作?这让我感到惊讶.
int为32位和long/ double或64位.这些尺寸是否保持相同
long/ double原子的?读取和写入对于引用变量和大多数原始变量(除long和double之外的所有类型)都是原子的.
这个陈述与jvm/processor架构有什么关系吗?有人可以解释一下.
3.如果我使用64位jvm和处理器,最后我将能够读/写双/长原子
假设我在synchronized方法中更新了两个变量的值.在退出synchronized块之前,同步方法中设置的新值是否可能对其他线程可见?
public synchronized void setValues(){
a=5;
// assume thread is preempted after this assignment
// would the value 5 be visible to other threads?
// my understanding is that the values will not be flushed to
// main memory until the lock is released- i.e., until the synchronized
// method is complete. So the changes will not be visible to other
// threads even when not using synchronization
b=10;
}
Run Code Online (Sandbox Code Playgroud)
下面的方法不同步,所以我理解该线程可能会 看到陈旧的值.我的问题是,如果线程在分配给a之后被抢占,那么变量a的新值"5"是否可能在printValues方法中可见?
public …Run Code Online (Sandbox Code Playgroud)