1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 |
public
class Singleton { private
static volatile Singleton singleton = null ; //volatile阻止JVM对指令执行顺序的优化,防止乱序执行导致导致返回的实例为半成品 private
void Singleton() {} public
static Singleton getInstance() { if
(singleton == null ) { synchronized
(Singleton. class ) { if
(singleton == null ) { //双重检查,如果第二个线程进入不做检查会产生不同的实例 singleton = new
Singleton(); } } } return
singleton; } public
static void main(String[] args) { System.out.println(Singleton.getInstance() == Singleton.getInstance()); } } |
原文:http://www.cnblogs.com/easylifesh/p/3614152.html