对于volatile的理解,我想通过代码来表达。
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco; color: #931a68 }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco; min-height: 25.0px }
p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco; color: #4e9072 }
span.s1 { color: #931a68 }
span.s2 { color: #000000 }
span.s3 { color: #0326cc }
span.Apple-tab-span { white-space: pre }
public class VolatileExample {
private volatile long data;
public void setData(long newData){
data = newData;//对于volatile变量的写
}
public long getData(){
return data;//对于volatile变量的读
}
public void increseData(){
data++;//对于volatile变量的复合操作
}
}
等价于下面这个类:
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco }
p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco; color: #931a68 }
p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco; min-height: 25.0px }
p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Monaco; color: #4e9072 }
span.s1 { color: #931a68 }
span.s2 { color: #000000 }
span.s3 { color: #0326cc }
span.Apple-tab-span { white-space: pre }
public class VolatileExampleNew {
private volatile long data;
public synchronized void setData(long newData){
data = newData;//对于volatile变量的写
}
public synchronized long getData(){
return data;//对于volatile变量的读
}
public void increseData(){
long temp = getData();
temp+=1l;
setData(temp);
}
}