forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT2.java
More file actions
87 lines (74 loc) · 1.58 KB
/
T2.java
File metadata and controls
87 lines (74 loc) · 1.58 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package books; /**
* @program JavaBooks
* @description: 单例模式
* @author: mf
* @create: 2019/08/15 15:53
*/
/**
* 饿汉
*/
public class T2 {
private static T2 instance = new T2();
private T2(){}
public static T2 getInstance() {
return instance;
}
}
/**
* 饿汉变种
*/
class Singleton1 {
private static Singleton1 instance = null;
static {
instance = new Singleton1();
}
private Singleton1() {}
public static Singleton1 getInstance() {
return instance;
}
}
/**
* 懒汉 -- 线程不安全...
*/
class Singleton2 {
private static Singleton2 instance = null;
private Singleton2(){}
public static Singleton2 getInstance() {
if (instance == null){
instance = new Singleton2();
}
return instance;
}
}
/**
* 懒汉 -- 线程安全, 但消耗资源较为严重
*/
class Singleton3 {
private static Singleton3 instance = null;
private Singleton3() {
}
public static synchronized Singleton3 getInstance() {
if (instance == null) {
instance = new Singleton3();
}
return instance;
}
}
/**
* 线程安全,双重校验
*/
class Singleton4 {
private static volatile Singleton4 instance = null;
private Singleton4() {
}
public static Singleton4 getInstance() {
if (instance == null) {
synchronized (Singleton4.class) {
if (instance == null) {
instance = new Singleton4();
}
}
}
return instance;
}
}