hopeofthevillage

单例模式最终推荐写法-线程安全

2020-06-10 08:55  全me村的希望  阅读(...)  评论(...编辑  收藏

最终推荐写法

public class Singleton{

        private static class SingletonHolder{

           public static Singleton instance = new Singleton();  
    } 
    private Singleton(){}
    //访问静态内部类的静态字段 从而触发类的加载  
    public static Singleton newInstance(){
       return SingletonHolder.instance;  
    }             
}

  因为同一个类只加载一次,类加载过程由类加载器负责加载,从而保证线程安全。相对于双重检测锁,更加简洁。

相关文章:

猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
  • 2021-12-12
  • 2021-06-08
相关资源
相似解决方案