public class Test3 {
static class A{
int i =0 ;
public void setAto60(){
i = 60;
}
}
public static void main(String[] args) {
A a = new A();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("current-Thread:"+Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
a.setAto60();
System.out.println("current-Thread:"+Thread.currentThread().getName()+"--a:"+a.i);
}
},"AA").start();
while(a.i==0){
}
System.out.println("end");
}
}
没有加volatile,子线程修改了a.i,没有通知主线程,主线程的a.i一直为0
i添加volatile,子线程修改后会通知主线程
volatile int i;