这段代码为什么会输出a:1,b:3呢, 我加了volatile关键字,不是一个线程修改了值,对另一个线程可见吗 ?
public class Test4 {
//加了volatile,为什么会出现: a:1,b:3
volatile long a = 1;
volatile long b = 2;
public void change(){
a = 3;
b = a;
}
public void print(){
System.out.println("a:"+a+",b:"+b);
}
public static void main(String[] args) {
while (true){
final Test4 test4 = new Test4();
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
test4.change();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
test4.print();
}
}).start();
}
}
}