??????java????????????У???????????volatile??????????????????????????????????????ж?????????????????????′???
????Java??????????????????????????????????????????????? ????? ?? volatile ?????????
????synchronized
??????????????????????? synchronized ??????????????м???synchronized ?? ???????????????????????????????????????
????synchronized ???ε???? ???? ????顣
????volatile
??????volatile???ε????????????????????????????????????????????volatile??????????????????????????????
????volatile?????????
??????????????????????С????????????????????????????????????????????????????????????????????volatile???ε????????? ????????????????a??????????????????и????????????????????????????????????????????????????????????????????й????? ????????volatile???Σ???????????a???????????????????????a????????????????????.
????volatile???????“????”
???????濴????????????????????????????????????????????ü?????inc????????????????м??
??????л???——jdk?汾??jdk1.6.0_31 ????? ??3G   cpu??x86 2.4G
public class Counter {
public static int count = 0;
public static void inc() {
//???????1??????y??????
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
count++;
}
public static void main(String[] args) {
//?????1000???????????i++?????????????
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Counter.inc();
}
}).start();
}
//??????????е?????п????????????1000
System.out.println("???н??:Counter.count=" + Counter.count);
}
}
???????н??:Counter.count=995
???????????????ο?????????????????????????н??:Counter.count=995??????????????????????£?Counter.count??????????????1000
???????????????????????????????????????count??????volatile????????????????????????????????????????????????????????
public class Counter {
public volatile static int count = 0;
public static void inc() {
//???????1??????y??????
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
count++;
}
public static void main(String[] args) {
//?????1000???????????i++?????????????
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Counter.inc();
}
}).start();
}
//??????????е?????п????????????1000
System.out.println("???н??:Counter.count=" + Counter.count);
}
}
???????н??:Counter.count=992