public class NoVisibility {
private static boolean ready;
private static int num;
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
while (!ready) {
}
System.out.println("num:" + num);
}
}).start();
Thread.sleep(1000);
num = 20;
ready = true;
}
}
求助各位大牛,上面的代码在-server的jvm中 无限循环,一直没想通,主线程设置ready=true,循环的线程为什么会无限循环呢?
Thread.sleep(1000);,,,主线程停了1秒,,,然后等待cpu,,,一直竞争不到,
所以ready = true;,,,没执行,,
【1】可以设置线程的优先级,,吧你这个线程优先级降低一点,,
【2】while循环里加点耗时操作,,