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
Des instructions comme
a = a + 1
eta = a - 1
impliquent en fait trois opérations : lecture-modification-écriture :Lire la variable à un certain emplacement de la pile
Ajouter (soustraire) 1 à la valeur à cette position dans la pile
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 pasa = a + 1
eta = a - 1
impliqués dans les trois opérations ci-dessus atomiques. Afin d'assurer la synchronisation, vous devez utilisersynchronized
:Le résultat d'une certaine opération :
(Là où td1 apparaît, a vaut +1 ; là où td2 apparaît, a vaut -1)