dzbkq_110 2017-04-21 14:35 采纳率: 25%
浏览 897
已结题

为什么打印输出全是0,而第二种情况输出是42

package com.my.current;

public class NoVisibility {

private static  volatile boolean ready;
private static   int number;
private static class ReaderThread extends Thread{
    public void run(){
        while(!ready){

            System.out.println(number);
        }
        //while(!ready);
        //System.out.println(number);
    }
}

public static void main(String[] args) throws InterruptedException{

    new ReaderThread().start();
    Thread.sleep(1000);
    number = 42;
    ready = true;
    Thread.sleep(1000);
}

}

  • 写回答

6条回答 默认 最新

  • threenewbee 2017-04-21 14:39
    关注
     第一个是
    while(!ready)
    {
    System.out.println(number);
    }
    第二个相当于
    while(!ready)
    {
    }
    System.out.println(number);
    
    一个是ready以前输出,一个是以后输出。
    
    评论

报告相同问题?