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

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

répondre à tous(1)
迷茫

Des instructions comme

a = a + 1 et a = a - 1 impliquent en fait trois opérations : lecture-modification-écriture :

  1. Lire la variable à un certain emplacement de la pile

  2. Ajouter (soustraire) 1 à la valeur à cette position dans la pile

  3. Réécrivez la valeur incrémentée à l'emplacement de stockage correspondant à la variable

Ainsi, bien que la variable a soit modifiée avec volatile, elle ne rend pas a = a + 1 et a = a - 1 impliqués dans les trois opérations ci-dessus atomiques. Afin d'assurer la synchronisation, vous devez utiliser 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();

    }
}

Le résultat d'une certaine opération :

(Là où td1 apparaît, a vaut +1 ; là où td2 apparaît, a vaut -1)

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!