1
/**
2
* @author lx
3
* 線程不安全的單例,試想兩個線程都進入了if(singleton==null)塊里這個時候會初始化兩個對象,這只在第一次調用的時候會產生
4
*/
5
public class Unsafe_singleton {
6
7
private static Unsafe_singleton singleton;
8
9
private Unsafe_singleton() {
10
}
11
12
public static Unsafe_singleton getInstance() {
13
if (singleton == null) {
14
singleton = new Unsafe_singleton();
15
}
16
return singleton;
17
}
18
}
19
public class Safe_singleton {
20
21
private static Safe_singleton singleton;
22
23
private Safe_singleton() {
24
}
25
26
/**
27
* 這種寫法,非常消耗性能,因為只是第一次進來的時候可能會產生多個實例的情況,后面多線程都不會再進行實例化,那么調用的時候會很降低性能
28
* @return
29
*/
30
public static synchronized Safe_singleton getInstance() {
31
if (singleton == null) {
32
singleton = new Safe_singleton();
33
}
34
return singleton;
35
}
36
}
37
/**
38
* @author lx
39
* 這種寫法如果在創建和運行時的負擔不太繁重,那么這種寫法也可以保證多線程安全,每個線程進來都會new 創建此實例。
40
* 這種單例相對于每個線程來說確實是唯一的
41
*/
42
public class MoreSafe_singleton {
43
44
private static MoreSafe_singleton singleton = new MoreSafe_singleton();
45
46
public static MoreSafe_singleton getInstance(){
47
return singleton;
48
}
49
}
50
/**
51
* @author lx
52
* volatile 這個只在JDK1.5以上出現 它確保singleton變量被初始化時,多個線程正確地處理singleton變量
53
* 這種寫法如果性能是關注的重點,那么可以大大減少getInstance()的時間消耗
54
*/
55
public class VerySafe_singleton {
56
57
private volatile static VerySafe_singleton singleton;
58
private VerySafe_singleton(){}
59
60
public static VerySafe_singleton getInstance(){
61
if(singleton==null){
62
synchronized(VerySafe_singleton.class){
63
if(singleton==null){ //里面為何在加上判斷是否為空?
64
//因為試想如果有三個線程其中一個線程剛剛走出synchronized塊,這個時候又進來一個線程,
65
//如果不判斷是否為空,這個又會實例一個變量那么就不是單例了
66
singleton=new VerySafe_singleton();
67
}
68
}
69
}
70
return singleton;
71
}
72
}

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
