Java??volatile?????????
???????????? ???????[ 2016/2/19 13:55:08 ] ??????????????????? ???????
??????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
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11