续上一篇👉单例模式-详解
再来探讨下【单例模式-懒汉式】是怎么个不安全法?
来看存在线程风险的代码~
单例模式-懒汉式
package singleton.demo;
/*懒汉式-单例模式*/
public class SingletonTwo {
/*定义一个私有构造方法*/
private SingletonTwo(){}
/*定义一个私有的静态成员属性将该对象的引用指向null*/
private static SingletonTwo instance = null;
/*提供一个获取该类对象的共有静态方法,第一次调用该方法的时候会创建该类的实例对象并且将其保存在静态成员属性中*/
public static SingletonTwo getInstance() throws InterruptedException {
if (instance == null){
/*倘若此处该线程进入阻塞状态,而同时运行该程序另一条线程成功的进入if语句块,结果可想而知*/
instance = new SingletonTwo();
}
return instance;
}
}
我们知道懒汉式的单例模式,创建对象的时机在第一次调用getInstance()方法。而安全隐患就存在这时间段,倘若有两条线程都是运行该代码段,一条线程运行过程进入了if语句块且还没有把创建对象的实例赋值给成员变量时恰好进入了阻塞状态(还不清楚线程生命周期的小伙伴可理解为该线程暂停了)。由于if语句判断条件依据是:instance == null才能进入该语句块。那么另一条线程就有可能会混进在该if语句块,最后就会导致两个线程创建了两个不一样的对象。
导致【单例模式-懒汉式】返回不同对象的“剧本”已经写好了,上代码:
微改一下实现单例的类:
在刚进入语句块时调用Thread.sleep(3000)让该线程休眠三秒钟。
package singleton.demo;
/*懒汉式-单例模式*/
public class SingletonTwo {
/*定义一个私有构造方法*/
private SingletonTwo(){}
/*定义一个私有的静态成员属性将该对象的引用指向null*/
private static SingletonTwo instance = null;
/*提供一个获取该类对象的共有静态方法,第一次调用该方法的时候会创建该类的实例对象并且将其保存在静态成员属性中*/
public static SingletonTwo getInstance() throws InterruptedException {
if (instance == null){
Thread.sleep(3000);
instance = new SingletonTwo();
}
return instance;
}
}
package singleton.test;
import singleton.demo.SingletonTwo;
public class ThreadTest implements Runnable{
public static void main(String[] args) {
/*
创建两个线程,并启用,启用后线程即进入了可运行状态,等待获取cpu资源,
获取到cup资源后会自动调用run()方法。
*/
Thread thread1 = new Thread(new ThreadTest());
thread1.start();
Thread thread2 = new Thread(new ThreadTest());
thread2.start();
}
@Override
public void run() {
SingletonTwo singletonTwo = null;
try {
singletonTwo = SingletonTwo.getInstance();
System.out.println(singletonTwo);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
由于线程运行是不确定的,因此有时候得尝试多遍后才会出现返回不同对象的运行结果:
返回相同对象的运行结果:
返回不同对象的运行结果:
接下来我们可以使用synchronized 修饰符去修饰getInstance()方法。
package singleton.demo;
/*懒汉式-单例模式*/
public class SingletonTwo {
/*定义一个私有构造方法*/
private SingletonTwo(){}
/*定义一个私有的静态成员属性将该对象的引用指向null*/
private static SingletonTwo instance = null;
/*提供一个获取该类对象的共有静态方法,第一次调用该方法的时候会创建该类的实例对象并且将其保存在静态成员属性中*/
synchronized public static SingletonTwo getInstance() throws InterruptedException {
if (instance == null){
Thread.sleep(3000);
instance = new SingletonTwo();
}
return instance;
}
}
这样就可以保证多线程下,依然能够完整的运行getInstance(),即使休眠,其他线程也得等我睡醒。hhh。
以上这种方式叫做“同步锁”即使用synchronized关键字实现线程的锁定。当然还有其他方法可以达到这种效果。比如说:双重校验锁,静态内部类,枚举来去保证操作时的线程唯一。