单列模式就是这个类只允许有一个对象,单列模式又分懒汉式和饿汉式,下面我们通过代码来看看懒汉式和饿汉式的区别:
1.懒汉式
public class SingletonLazy {
// volatile:将singleton设置为可见性(每个线程都只能从主内存获取singleton)
private static volatile SingletonLazy singletonLazy = null;
private SingletonLazy() {}
/**
* 方法用途: 获取对象<br/>
* 操作步骤: TODO<br/>
* ${tags}
*/
public static SingletonLazy getInstance() {
// singleton是可见的,如果有线程已经创建了singleton对象,这里不为null,直接返回singleton对象
if (null == singletonLazy) {
// 加上synchronized同步锁,只能有一个线程访问
synchronized (SingletonLazy.class) {
// 二次判断singleton对象是否还没有被创建
if (null == singletonLazy) {
singletonLazy = new SingletonLazy();
}
}
}
return singletonLazy;
}
}
这里我们为什么要加synchronized呢?
因为懒汉式他是线程不安全的;singletonLazy 初始化是null,如果多个线程同时获取singletonLazy对象,每个线程都会去new一个SingletonLazy,这样就变成了多例了;所以我们在singletonLazy = new SingletonLazy()这段代码加上synchronized,二次判断singletonLazy是否为空,这样就解决了多线程并发访问线程安全的问题。
2.饿汉式:
public class SingletonHunger {
private static SingletonHunger singletonHunger = new SingletonHunger();
private SingletonHunger() {}
public static SingletonHunger getInstance() {
return singletonHunger;
}
}
因为饿汉式在程序启动的时候就创建singletonHunger对象,所以不存在线程安全问题。