java - 線程同步為什么不一樣
問題描述
package com.dome;
public class Thread01 {
private volatile static int a =10;Thread td1 = new Thread(){public void run(){for(int i=0;i<3;i++){ a = a+1;System.out.println(i+'td1:='+a);} } };Thread td2 = new Thread(){ public void run(){for(int i=0;i<3;i++){ a -=1; System.out.println(i+'td2:='+a);} } };public static void main(String[] args) { Thread01 th = new Thread01(); th.td1.start();th.td2.start(); }
}
0td1:=90td2:=91td1:=101td2:=92td1:=102td2:=9
問題解答
回答1:a = a + 1, a = a - 1 這樣的語句,事實上涉及了 讀取-修改-寫入 三個操作:
讀取變量到棧中某個位置
對棧中該位置的值進行加 (減)1
將自增后的值寫回到變量對應(yīng)的存儲位置
因此雖然變量 a 使用 volatile 修飾,但并不能使涉及上面三個操作的 a = a + 1,a = a - 1具有原子性。為了保證同步性,需要使用 synchronized:
public class Thread01 { private volatile static int a = 10; Thread td1 = new Thread() {public void run() { for (int i = 0; i < 3; i++) {synchronized (Thread01.class) { a = a + 1; System.out.println(i + 'td1:=' + a);} }} }; Thread td2 = new Thread() {public void run() { for (int i = 0; i < 3; i++) {synchronized (Thread01.class) { a -= 1; System.out.println(i + 'td2:=' + a);} }} }; public static void main(String[] args) {Thread01 th = new Thread01();th.td1.start();th.td2.start(); }}
某次運行結(jié)果:
(td1 出現(xiàn)的地方,a 就 +1;td2 出現(xiàn)的地方,a 就 -1)
相關(guān)文章:
1. javascript - 在靜態(tài)頁面上用load 引入的頁面文件問題?2. javascript - webpack打包后的bundlejs文件代碼不知道什么意思.3. Java游戲服務(wù)器開發(fā)和網(wǎng)站、app服務(wù)端的開發(fā)都差不多的嗎???實現(xiàn)的思路和方法4. android - RxJavar用什么操作符可以使數(shù)據(jù)每隔一段時間取出一個5. java后臺導(dǎo)出頁面到pdf6. css - 關(guān)于ul的布局7. css - 如何使用 vue transition 實現(xiàn) ios 按鈕一樣的平滑切換效果8. java - oracle對漢字字段按照拼音排序的函數(shù)和sql語句是什么?9. javascript - vue組件通過eventBus通信時,報錯a.$on is not a function10. html - 哪些情況下float會失效?
