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
a = a + 1
,a = a - 1
Such a statement actually involves three operations: read-modify-write:Read the variable to a certain location on the stack
Add (subtract) 1 to the value at this position in the stack
Write the self-incremented value back to the storage location corresponding to the variable
So while variable a uses
volatile
修饰,但并不能使涉及上面三个操作的a = a + 1
,a = a - 1
具有原子性。为了保证同步性,需要使用synchronized
:The result of a certain operation:
(Where td1 appears, a is +1; where td2 appears, a is -1)