单例模式
/** * 不是线程安全的 */ public class UnsafeSingleton { private static UnsafeSingleton uniqueInstance; private UnsafeSingleton() { } public static UnsafeSingleton getInstance() { if(uniqueInstance == null) { uniqueInstance = new UnsafeSingleton(); } return uniqueInstance; } }
线程安全的三种做法:
1.同步代码块。效率低。
2.属性上初始化对象。
3.用双重检查锁,首先检查实例是否已经创建。如果没有创建才进行同步。
/**
* 1.加上synchronized关键字。但是效率低。
*/
public class SafeSingleton1 {
private static SafeSingleton1 uniqueInstance;
private SafeSingleton1() {
}
public static synchronized SafeSingleton1 getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new SafeSingleton1();
}
return uniqueInstance;
}
}
/**
* 2.jvm加载时创建实例
*/
public class SafeSingleton2 {
//依赖JVM在加载这个类时马上创建此唯一的实例。JVM保证在任何线程访问静态变量前,一定先创建此实例。
public static SafeSingleton2 instance = new SafeSingleton2();
private SafeSingleton2(){
}
public static SafeSingleton2 getInstance() {
return instance;
}
}
/**
* 3.
* 先检查实例是否创建,如果没创建才进行同步。
* 这样只有第一次会同步。
*/
public class SafeSingleton3 {
private static volatile SafeSingleton3 instance;
private SafeSingleton3(){
}
public static SafeSingleton3 getInstance() {
if(instance == null) {
synchronized(SafeSingleton3.class) {
if(instance == null) {
instance = new SafeSingleton3();
}
}
}
return instance;
}
}

浙公网安备 33010602011771号