/*单例类(饿汉模式)*/
public class Singleton {
//step2自行对外提供实例
private static final Singleton singleton = new Singleton();
//step1构造函数私有化
private Singleton(){}
//step3提供外界可以获得该实例的方法
public static Singleton getSingleton() {
return singleton;
}
}
/*单例模式的懒汉模式,普通懒汉模式有线程问题,需要加synchronized,添加synchronized锁虽然可以保证线程安全,
但是每次访问getInstance()方法的时 候,都会有加锁和解锁操作,同时synchronized锁是添加在方法上面,锁的范围过大,而 单例类是全局唯一的,锁的操作会成为系统的瓶颈。
因此,需要对代码再进行优化,由此引出了“双重校验锁”的方式*/
class Singleton{
private static Singleton singleton = null;
private Singleton (){}
public static synchronized Singleton getSingleton() {
if (null == singleton){
singleton = new Singleton();
}
return singleton;
}
}
/*双重校验锁(会出现指令重排问题)什么是指令重排问题请百度*/
class Singleton{
private static Singleton singleton = null;
private Singleton (){}
public static Singleton getSingleton() {
if (null == singleton){
synchronized (Singleton.class){
if (null == singleton){
singleton = new Singleton();
}
}
}
return singleton;
}
}
/*双重校验锁(volatile解决指令重排问题)*/
class Singleton{
private static volatile Singleton singleton = null;
private Singleton (){}
public static Singleton getSingleton() {
if (null == singleton){
synchronized (Singleton.class){
if (null == singleton){
singleton = new Singleton();
}
}
}
return singleton;
}
}
/*
静态内部类单例模式(推荐用法)
* */
class __Singleton{
//2:私有的静态内部类,类加载器负责加锁
private static class SingletonHolder{
private static __Singleton singleton = new __Singleton();
}
//1.私有化构造方法
private __Singleton(){}
public static __Singleton getInstance(){
return SingletonHolder.singleton;
}
}
网友评论