大家好,又见面了,我是你们的朋友全栈君。
个人理解,单例是指单个实例,在整个应用程序当中有且仅有一个实例存在,该实例是通过代码指定好的(自行创建的)。
顾名思义,不管有没有使用到该对象,只要程序启动成功,该单实例对象就存在。
代码如下:
/** * 饿汉式 */
public class SingletonHungry {
private static SingletonHungry instance = new SingletonHungry();
public static SingletonHungry instance(){
return instance;
}
public static void main(String[] args) {
SingletonHungry instance1 = SingletonHungry.instance();
SingletonHungry instance2 = SingletonHungry.instance();
System.out.println(instance1);
System.out.println(instance2);
}
}上述情况,满足在单线程和多线程中使用。
顾名思义,只有在程序当中使用到该对象的时候,该单实例对象才会被实例化。
代码如下:
/** * 懒汉式-单线程 */
public class SingletonLazy {
public static SingletonLazy instance = null ;
public static SingletonLazy instance() {
if(instance == null) {
instance = new SingletonLazy() ;
}
return instance ;
}
}上述编写的代码中,乍一看,没问题,满足了单实例对象。可是细细一琢磨,咋感觉这不对,如果多线程情况下,就很难保证单实例对象了。下面提供一种多线程情况下实现单例的方式:
/** * 懒汉式-多线程 */
public class SingletonLazy {
public static SingletonLazy instance = null ;
public static SingletonLazy instance() {
if(instance == null ) {
synchronized (SingletonLazy.class) {
if(instance == null) {
instance = new SingletonLazy();
}
}
}
return instance ;
}
}上述的代码中满足了多线程的使用场景,就是使用了上锁+双重检查来进行实现。
欢迎交流!
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/169690.html原文链接:https://javaforall.cn