0%

设计模式-单例模式

设计模式-单例模式

单例模式仅创建一个实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package designpatterns;
/**
* 双检锁单例模式 懒汉式 线程安全 高性能
*/
public class Singleton {
/**
* volatile 关键字保证实例在多线程中的可见性以及防止指令重排序 创建实例的过程可以被分解成3个步骤 1. memery = allocate();
* // 分配内存空间 2. initialize(memery); // 初始化内存空间 3. instance = memery; //
* 将内存地址赋值给instance
*/
private static volatile Singleton instance;

/**
* 构造函数私有化防止被调用
*/
private Singleton() {

}

public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}

public static void main(String[] args) {
MyThread[] threads = new MyThread[5];
for (int i = 0; i < 5; i++) {
threads[i] = new MyThread(String.format("Thread-%d", i + 1));
threads[i].start();
}
}
}

class MyThread extends Thread {
String name;

public MyThread(String name) {
this.name = name;
}

@Override
public void run() {
Singleton instance = Singleton.getInstance();
System.out.println(this.name + ":" + instance.hashCode());
}
}