Java实现单例模式有很多种实现方法,其中我们应根据需要选择线程安全的与非线程安全的两种方式,根据对象实现的方式又分为饱汉与饿汉方式。
这里使用java中的volatile关键字与synchronized关键字对单例进行双重加锁,保证了线程安全,当然这样效率就会稍微低点。下面是具体代码:
public class Singleton {  
  
  
    private volatile static Singleton instance=null;  
    private Singleton(){  
          
    }  
    public static Singleton getInstance(){  
        if(instance==null){  
            synchronized (Singleton.class) {  
                if(instance==null){  
                    instance=new Singleton();  
                }  
            }  
        }  
        return instance;  
    }  
}

02:实现Singleton模式02:实现Singleton模式

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-05
  • 2021-11-30
  • 2022-12-23
  • 2022-03-04
猜你喜欢
  • 2021-05-27
  • 2021-11-08
  • 2021-12-07
  • 2022-12-23
  • 2022-01-20
  • 2022-01-26
  • 2022-12-23
相关资源
相似解决方案