唉!今天笔者在面试中被一个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){
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(懒汉模式.getInstance().hashCode());
}
};
Thread threadA = new Thread(runnable);
Thread threadB = new Thread(runnable);
Thread threadC = new Thread(runnable);
Thread threadD = new Thread(runnable);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
}
}
用了double check 的懒汉式
懒汉式进阶 线程安全,懒加载,调用效率高
public class 懒汉模式加锁 {
//volatile 关键字防止指令重排
private volatile static 懒汉模式加锁 mode ;
private 懒汉模式加锁(){
}
public static 懒汉模式加锁 getInstance(){
try {
if (mode==null){
synchronized (懒汉模式加锁.class){
if (mode==null){
mode = new 懒汉模式加锁();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return mode;
}
public static void main(String[] args){
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("hashCode:"+懒汉模式加锁.getInstance().hashCode());
}
};
Thread threadA = new Thread(runnable);
Thread threadB = new Thread(runnable);
Thread threadC = new Thread(runnable);
Thread threadD = new Thread(runnable);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
}
}
静态内部类 线程安全,懒加载,调用效率高
public class 静态内部类 {
private 静态内部类() {
}
public void method(){
System.out.println("method....");
}
public static 静态内部类 getInstance(){
return StaticSingletion.INSTANCE;
}
public static class StaticSingletion{
private static final 静态内部类 INSTANCE = new 静态内部类();
}
public static void main(String[] args) {
Runnable rab = new Runnable() {
@Override
public void run() {
System.out.println(静态内部类.getInstance().hashCode());
}
};
Thread tha = new Thread(rab);
Thread thb = new Thread(rab);
Thread thc = new Thread(rab);
Thread thd = new Thread(rab);
tha.start();
thb.start();
thc.start();
thd.start();
}
}



