非线程安全的懒汉式单例
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
// 如果多个线程同时进来,会产生多个实例
instance = new Singleton();
}
return instance;
}
}
/**
* synchronized对整个方法加锁,形成同步机制,
* 这样虽然解决了线程安全问题,但是会产生性能问题(不推荐)
*/
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
/**
* 双重检查锁
*/
public class DoubleCheckedLocking {
private volatile static DoubleCheckedLocking instance;
public static DoubleCheckedLocking getInstance() {
if (instance == null) {
// 如果同时有多个线程进来,还是会有线程安全问题,所以获取到锁之后还得再次判断是否为null
synchronized (DoubleCheckedLocking.class) {
if (instance == null)
instance = new DoubleCheckedLocking();
}
}
return instance;
}
}