文章目录
  1. 1. 概述:单例模式是最简单的,也是用的比较多的,这里记录一下常见几种单例的写法的优缺点。
  2. 2. 代码:
    1. 2.1. 饿汉式
    2. 2.2. 懒汉式
    3. 2.3. 用双重锁
    4. 2.4. 即实现懒加载又线程安全的方式

概述:单例模式是最简单的,也是用的比较多的,这里记录一下常见几种单例的写法的优缺点。

代码:

饿汉式

1
2
3
4
5
6
7
8
9
10
//线程安全但耗资源
class Singleton {
private static final Singleton instance = new Singleton();

private Singleton() { }

public static Singleton getInstance() {
return instance;
}
}

懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
class Singleton {   
private static Singleton instance = null; //延迟加载

private Singleton() { }

synchronized public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
  • 在方法上加锁:每次调用方法都用锁,效率低下,我们可以考虑在对象为null时才锁

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public static Singleton getInstance() {   
    if (instance == null) {
    //第二个线程进来了
    synchronized (Singleton.class) {
    //第一个线程走到这里
    instance = new Singleton();
    }
    }
    return instance;
    }
  • 这样做线程又不安全了如上注释

用双重锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Singleton {   
private volatile static Singleton instance = null;

private Singleton() { }

public static Singleton getInstance() {
//第一重判断
if (instance == null) {
//锁定代码块
synchronized (Singleton.class) {
//第二重判断
if (instance == null) {
instance = new Singleton(); //创建单例实例
}
}
}
return instance;
}
}

即实现懒加载又线程安全的方式

1
2
3
4
5
6
7
8
9
10
11
12
class Singleton {  
private Singleton() {
}

private static class HolderClass {
private final static Singleton instance = new Singleton();
}

public static Singleton getInstance() {
return HolderClass.instance; //初始化类时才初始化外部类对象:懒加载
}
}
文章目录
  1. 1. 概述:单例模式是最简单的,也是用的比较多的,这里记录一下常见几种单例的写法的优缺点。
  2. 2. 代码:
    1. 2.1. 饿汉式
    2. 2.2. 懒汉式
    3. 2.3. 用双重锁
    4. 2.4. 即实现懒加载又线程安全的方式