Maison > Questions et réponses > le corps du texte
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
迷茫2017-04-18 10:56:18
Des instructions comme
a = a + 1
et a = 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 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)