当前位置: 代码迷 >> J2SE >> 这段代码Last str是2,哪位高手能告诉小弟我为什么
  详细解决方案

这段代码Last str是2,哪位高手能告诉小弟我为什么

热度:97   发布时间:2016-04-23 20:22:50.0
这段代码Last str是2,谁能告诉我为什么?
public class ShadowTest
{
    
    public static void main(String[] args)
    {
        final long startTime = System.currentTimeMillis();
        
        final long endTime = startTime + 2000L;
        
        new Thread(()->
        {
            while (System.currentTimeMillis() < endTime)
            {
                new Thread(new Read()).start();
            }
        }).start();
        
        try
        {
            Thread.currentThread().sleep(1000L);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Config.getConfig().update();
        System.out.flush();
        System.out.println("update----------------------------------------------------------");
        Config.getConfig().update();
        System.out.flush();
        System.out.println("update----------------------------------------------------------");
        
        try
        {
            Thread.currentThread().sleep(2000L);
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        String str = Config.getConfig().getStr();
        System.out.println("Last str=" + str); 
    }
    
}

class Config
{
    private static Config config = new Config();
    
    private static volatile int i = 0;
    
    private Config()
    {
        System.out.println("construct.....");
        System.out.println(i);
        str = Integer.toString(++i);
        System.out.println(i);
        System.out.flush();
    }
    
    private String str = null;
    
    public static Config getConfig()
    {
        return config;
    }
    
    public void update()
    {
        System.out.println("update...." + i);
        config = new Config(); 
        System.out.println("update~~~" + i);
        System.out.flush();
    }
    
    public String getStr()
    {
        return str;
    }
}

class Read implements Runnable
{

    @Override
    public void run()
    {
        String str = Config.getConfig().getStr();
        System.out.println("str=" + str);
        System.out.flush();
  相关解决方案