单例:一个进程中只能存在唯一一个对象。
1.饿汉模式。 主动型太粗暴。
/**
* @author :jiaolian
* @date :Created in 2021-01-10 21:25
* @description:饿汉单例测试
* @modified By:
* 公众号:叫练
*/
public class HungerSignletonTest {
//类初始化会创建单例对象
private static HungerSignletonTest signleton = new HungerSignletonTest();
private HungerSignletonTest(){};
public static HungerSignletonTest getInstance() {
return signleton;
}
public static void main(String[] args) {
//三个线程测试单例,打印hashcode是否一致
new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();
new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();
new Thread(()->{System.out.println(HungerSignletonTest.getInstance().hashCode()); }).start();
}
}
饿汉模式是主动创建对象,如上面程序代码,JDK1.8环境中主线程启动三个线程获取HungerSignletonTest实例的hashcode是否为同一个对象,测试结果如下图所示,所有的hashcode一致证明程序只有一个实例。饿汉单例在类初始化会提前创建对象。缺点:**过早的创建对象需要提前消耗内存资源,我们需要在使用单例对象时再去创建。**下面我们看看懒汉模式代码。
2.懒汉模式 线程不安全
/**
* @author :jiaolian
* @date :Created in 2021-01-10 21:39
* @description:懒汉设计模式测试
* @modified By:
* 公众号:叫练
*/
public class LazySignletonTest {
private static LazySignletonTest signleton = null;
private LazySignletonTest(){};
public static LazySignletonTest getInstance() {
if (signleton == null) {
/*try {
//创建对象睡2秒
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
signleton = new LazySignletonTest();
}
return signleton;
}
public static void main(String[] args) {
//三个线程测试单例
new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();
new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();
new Thread(()->{System.out.println(LazySignletonTest.getInstance().hashCode()); }).start();
}
}
懒汉模式是需要用到单例才调用getInstance()方法创建对象,看上去没有什么问题,如果放开上面注释语句,在创建对象睡2秒,可能得到的结果如下图所示,三个线程得到的hashcode的值并不一样,说明signleton对象不是单例。在延迟的情况下,所有线程都会进入if条件语句,所以会有如下情况。