请问下大家多线程的一个问题,为什么不使用volatile依然能够满足可见性呢?

TheLast 6月前 ⋅ 559 阅读

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也有可见性吗?请大家帮忙看看谢谢!


全部评论: 0

    我有话说: