File tree 2 files changed +36
-7
lines changed 2 files changed +36
-7
lines changed Original file line number Diff line number Diff line change 1
1
package singleton ;
2
2
3
- /**
4
- * 饿汉式。在类中实例化,外部调用时直接返回单例。
5
- */
6
3
public class Singleton {
7
- private static Singleton singleton =new Singleton ();
8
- //构造器私有化
9
- private Singleton (){
4
+ /**
5
+ * 懒汉式。先声明,等要用的时候再实例化。
6
+ * 使用volatile修饰,保证可见性。
7
+ */
8
+ private static volatile Singleton singleton =null ;
10
9
10
+ private Singleton (){
11
+ //..
11
12
}
12
13
13
- public static Singleton getInstance (){
14
+ /**
15
+ * 使用双重检查锁,保证线程安全。
16
+ * static修饰为静态变量,可以直接
17
+ */
18
+ public static Singleton getSingleton () {
19
+ if (singleton ==null ) {
20
+ synchronized (singleton ) {
21
+ if (singleton ==null ) {
22
+ singleton =new Singleton ();
23
+ }
24
+ }
25
+ }
14
26
return singleton ;
15
27
}
28
+
16
29
}
Original file line number Diff line number Diff line change
1
+ package singleton ;
2
+
3
+ /**
4
+ * 饿汉式。在类中实例化,外部调用时直接返回单例。
5
+ */
6
+ public class Singleton1 {
7
+ private static Singleton1 singleton1 =new Singleton1 ();
8
+ //构造器私有化
9
+ private Singleton1 (){
10
+
11
+ }
12
+
13
+ public static Singleton1 getInstance (){
14
+ return singleton1 ;
15
+ }
16
+ }
You can’t perform that action at this time.
0 commit comments