java - 线程同步为什么不一样
ringa_lee
ringa_lee 2017-04-18 10:54:18
0
1
466

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:=9
0td2:=9
1td1:=10
1td2:=9
2td1:=10
2td2:=9

ringa_lee
ringa_lee

ringa_lee

全部回覆(1)
迷茫

a = a + 1a = a - 1 這樣的語句,事實上涉及了 讀取-修改-寫入 三個運算:

  1. 讀取變數到堆疊中某個位置

  2. 對棧中該位置的值加 (減)1

  3. 將自增後的值寫回變數對應的儲存位置

因此雖然變數 a 使用 volatile 修饰,但并不能使涉及上面三个操作的 a = a + 1a = 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)

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!