作者:TheLast
发布时间:2020-04-02T20:05:54
public class VolatileCase { private static boolean ready; private static int number;
private static class PrintThread extends Thread{
@Override
public void run() {
System.out.println("PrintThread is running.......");
while(!ready);
System.out.println("number = "+number);
}
}
public static void main(String[] args) {
new PrintThread().start();
SleepTools.second(1);
number = 51;
ready = true;
SleepTools.second(5);
System.out.println("main is ended!");
}
}
这是我打印的结果
PrintThread is running....... number = 51 main is ended!
为什么不使用volatile,子线程依然能够知道ready变成了true呢。难道static也有可见性吗?请大家帮忙看看谢谢!