单例模式
-
单例模式(饿汉式)
public class Demo { public static void main(String[] args) throws IOException { // 获取Singleton对象 Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); System.out.println(s1 == s2); } } class Singleton { private static Singleton _instance = new Singleton(); // 私有构造方法 private Singleton() { } /** * 获取本类对象(饿汉式) * * @return Singleton */ public static Singleton getInstance() { return Singleton._instance; } }
-
单例模式(懒汉式)
public class Demo { public static void main(String[] args) throws IOException { // 获取Singleton对象 Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); System.out.println(s1 == s2); } } class Singleton { private static Singleton _instance = null; // 私有构造方法 private Singleton() { } /** * 获取本类对象(懒汉式) * * @return Singleton */ public static Singleton getInstance() { if (Singleton._instance == null) { Singleton._instance = new Singleton(); } return Singleton._instance; } }
推荐饿汉式
==在懒汉式下,多线程会创建多个对象。排除多线程后,可以使用懒汉式。==
- 解决单例模式线程安全
// 解决方案1
public class Demo {
public static void main(String[] args) throws IOException {
// 获取Singleton对象
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
}
}
class Singleton {
private static Singleton _instance = null;
// 私有构造方法
private Singleton() {
}
/**
* 获取本类对象(懒汉式)
*
* @return Singleton
*/
public static Singleton getInstance() {
if (Singleton._instance == null) {
synchronized (Singleton.class){
if(Singleton._instance == null){
Singleton._instance = new Singleton();
}
}
}
return Singleton._instance;
}
}
// 解决方案2
public class Demo {
public static void main(String[] args) throws IOException {
// 获取Singleton对象
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);
}
}
class Singleton {
// 私有构造方法
private Singleton() {
}
/**
* 获取本类对象(懒汉式)
*
* @return Singleton
*/
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
/**
* 单例模式类锁
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}
以上两种现成安全方案可以解决单例模式的线程安全问题
==说明:第二种方式在线程1进入方法后暂停,线程2进入方法后率先完成实例化,线程1再次实例化的时候由于INSTANCE是you由final修饰,所以不会创建多个对象!!!==