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
將自增后的值寫回到變量對應的存儲位置
因此雖然變量 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(); }}
某次運行結果:
(td1 出現的地方,a 就 +1;td2 出現的地方,a 就 -1)
相關文章:
1. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?2. 使用text-shadow可以給圖片加陰影嗎?3. angular.js - angularjs如何傳遞id給另一個視圖 根據id獲取json數據?4. 數據庫無法進入5. mysql - 記得以前在哪里看過一個估算時間的網站6. docker-compose 為何找不到配置文件?7. boot2docker無法啟動8. select - mysql怎么搜索一個字符串指定位置之后兩位9. python - linux怎么在每天的凌晨2點執行一次這個log.py文件10. 請問一下各位老鳥 我一直在學習獨孤九賤 現在是在tp5 今天發現 這個系列視頻沒有實戰
