参考文章链接:
http://www.blogjava.net/kenzhh/archive/2011/09/02/357824.html
1.懒汉模式-非线程安全
/**
* 懒汉-非线程安全
*
* @author John
*
*/
public class Singleton1 {
//声明静态的实例
private static Singleton1 instance;
//不允许自己创建实例化
private Singleton1() {}
//对外访问实例的静态方法
public static Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
}
2.懒汉模式-线程安全
/**
* 懒汉-线程安全
*
* @author John
*
*/
public class Singleton2 {
//声明静态的实例
private static Singleton2 instance;
//不允许自己创建实例化
private Singleton2() {}
//对外访问实例的静态方法,关键字synchronized表示该方法是线程同步的
public static synchronized Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}
return instance;
}
}
3.饿汉模式-声明时初始化-线程安全
/**
* 饿汉-线程安全
*
* @author John
*
*/
public class Singleton3 {
// 声明静态的实例,并在类加载的时候实例化,避免了多线程同步的问题
private static Singleton3 instance = new Singleton3();
// 不允许自己创建实例化
private Singleton3() {}
// 对外访问实例的静态方法
public static Singleton3 getInstance() {
return instance;
}
}
4.饿汉模式-static块中初始化-线程安全
/**
* 饿汉-线程安全-在static块初始化
*
* @author John
*
*/
public class Singleton4 {
// 声明实例
private static Singleton4 instance = null;
// 在static块中对实例进行初始化
static {
instance = new Singleton4();
}
// 不允许自己创建实例化
private Singleton4() {}
// 对外访问实例的静态方法
public static Singleton4 getInstance() {
return instance;
}
}
5.静态内部类-线程安全
/**
* 静态内部类-线程安全
*
* @author John
*
*/
public class Singleton5 {
// 定义静态内部类
private static class SingletonHolder {
// 将实例声明为静态常量,并初始化
private static final Singleton5 INSTANCE = new Singleton5();
}
// 不允许自己创建实例化
private Singleton5() {}
// 对外访问实例的静态方法,通过静态内部类访问
public static final Singleton5 getInstance() {
return SingletonHolder.INSTANCE;
}
}
6.枚举-线程安全
public enum Singleton6 {
INSTANCE;
public void whateverMethod() {
}
}
7.双重校验锁
public class Singleton7 {
private volatile static Singleton7 singleton;
private Singleton7() {}
public static Singleton7 getSingleton() {
if (singleton == null) {
synchronized (Singleton7.class) {
if (singleton == null) {
singleton = new Singleton7();
}
}
}
return singleton;
}
}