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 這樣的語句,事實(shí)上涉及了 讀取-修改-寫入 三個(gè)操作:
讀取變量到棧中某個(gè)位置
對棧中該位置的值進(jìn)行加 (減)1
將自增后的值寫回到變量對應(yīng)的存儲位置
因此雖然變量 a 使用 volatile 修飾,但并不能使涉及上面三個(gè)操作的 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(); }}
某次運(yùn)行結(jié)果:
(td1 出現(xiàn)的地方,a 就 +1;td2 出現(xiàn)的地方,a 就 -1)
相關(guān)文章:
1. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?2. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””3. mac里的docker如何命令行開啟呢?4. 關(guān)于docker下的nginx壓力測試5. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題6. nignx - docker內(nèi)nginx 80端口被占用7. docker容器呢SSH為什么連不通呢?8. 如何解決Centos下Docker服務(wù)啟動無響應(yīng),且輸入docker命令無響應(yīng)?9. docker start -a dockername 老是卡住,什么情況?10. dockerfile - 我用docker build的時(shí)候出現(xiàn)下邊問題 麻煩幫我看一下

網(wǎng)公網(wǎng)安備