zoukankan      html  css  js  c++  java
  • java语句顺序有时非常重要

    我们学习java时,通常被告知,变量定义的顺序不重要,可是下面程序确在jdk 1.7上执行出错。

    public class FactoryImpl implements Serializable {
        private final static  FactoryImpl INSTANCE = new FactoryImpl();
        private final static AtomicInteger count = new AtomicInteger(0);
    
        private int id;
    
        private FactoryImpl() {
            id = count.incrementAndGet();
        }
    
        public int getId() {
            return id;
        }
    
        public static FactoryImpl getInstance() {
            return INSTANCE;
        }
    
        public static void main(String[] args) {
            FactoryImpl impl1 = FactoryImpl.getInstance();
            System.out.println(impl1.id);
        }
    }

    把下面代码调整顺序之后能够运行成功。

        private static final FactoryImpl INSTANCE = new FactoryImpl();
        private final static AtomicInteger count = new AtomicInteger(0);

    原因例如以下,假设不调整时,当类被载入时,先初始化INSTANCE静态变量,这时,会调用FactoryImpl构造方法,在此构造方法里,调用count.incremnetAndGet();这时count还没有初始化。这是因为进行类载入时。静成变量的初始化顺序造成的。

  • 相关阅读:
    深入浅出HTTP协议
    HTTP协议 URL
    HTTP Request
    HTTP 响应
    浅谈OpenStack架构
    Google云平台技术架构
    接口文档神器之apidoc
    .haccess 配置生效
    php namespace与use
    mysql 带条件的sum/count 使用技巧
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7134212.html
Copyright © 2011-2022 走看看