Skip to content

Commit 4fe290e

Browse files
为了保证线程安全,单例模式使用volatile和双重检查锁。
1 parent 77dc5ed commit 4fe290e

File tree

2 files changed

+36
-7
lines changed

2 files changed

+36
-7
lines changed
Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,29 @@
11
package singleton;
22

3-
/**
4-
* 饿汉式。在类中实例化,外部调用时直接返回单例。
5-
*/
63
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;
109

10+
private Singleton(){
11+
//..
1112
}
1213

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+
}
1426
return singleton;
1527
}
28+
1629
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
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+
}

0 commit comments

Comments
 (0)