zoukankan      html  css  js  c++  java
  • 单例模式

    第一种:(懒汉)线程不安全

     public class Singleton {

      private static Singleton instance;

    private Singleton(){

    public static Singleton getInstance(){
    if(instance == null){

    instance = new Singleton();

    return  instance;

    }

     这种写法lazy loading很明显,但是致命的是在多线程不能正常工作。

     第二种:(懒汉)线程安全

    public class Singleton {

      private static Singleton instance;

    private Singleton(){}

    public static synchronized Singleton getInstance(){

     if(instance == null){

    instance = new Singleton(); 

    return instance; 

     

     这种写法能够在多线程中很好的工作,而且看起来它也具备很好的lazy loading,但是,遗憾的是,效率很低,99%情况下不需要同步。

     第三种:(饿汉)

    public class Singleton{

    private static Singleton instance = new Singleton();

    private Singleton(){}

    private static Singleton getInstance(){

      return instance;

    第四种:(饿汉,变种)

    public class Singleton{

      private static Singleton instance = null;

    static{

      instance = new Singleton();

      private Singleton(){}

    public static Singleton getInstance(){

      return instance;

      }

  • 相关阅读:
    大佬讲话听后感
    P1226快速幂取余
    对拍
    P1017 进制转换
    P1092 虫食算 NOIP2002
    P1003 铺地毯
    P1443 马的遍历
    P1032 字串变换
    P1379 八数码问题
    2-MAVEN 基本命令
  • 原文地址:https://www.cnblogs.com/vanl/p/4973783.html
Copyright © 2011-2022 走看看