唉!今天笔者在面试中被一个double check 给问懵了, 该死的面试官给爷拽英文 ,我没有联想到单例模式中的懒汉式。
首先,我给大家讲一下单例模式,单例模式是一种经典的设计模式,它用来确保我们程序中只会存在一个实例对象引用(只有一个),单例的目标是线程安全,懒加载,调用效率高。常见的单例模式有以下几种
饿汉式 线程安全,非懒加载,调用效率高
用私有的构造方法 创建对象,在给你一个公开的方法获取该对象;
public class 饿汉模式 {
private static 饿汉模式 饿汉 = new 饿汉模式();
private 饿汉模式() {
}
private static 饿汉模式 getInstance(){
return 饿汉;
}
public static void main(String[] args){
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Get hashCode: " + 饿汉模式.getInstance().hashCode());
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
Thread thread3 = new Thread(runnable);
Thread thread4 = new Thread(runnable);
Thread thread5 = new Thread(runnable);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
懒汉式 线程不安全,懒加载,调用效率低
public class 懒汉模式 {
private static 懒汉模式 mode = null;
private 懒汉模式() {
}
public static 懒汉模式 getInstance(){
if(mode!=null){
return mode;
}
try {
Thread.sleep(2000); // 模拟生成实例前做一些准备工作
mode = new 懒汉模式();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mode;
}
public static void main(String[] args){