多线程环境下单例模式(java23中设计模式)
一,在类加载时创建实例化单例对象(线程安全,并且不需要同步);
package test;
/**
* @author Administrator
* 多线程变成单例模式——1
*/
public class SingletonTest {
//类加载是创建一个对象
private static SingletonTest singleton = new SingletonTest();
//私有构造方法,防止被实例化
private SingletonTest(){
}
//获取单例对象
public SingletonTest getInstance(){
return singleton;
}
}
二,双重判断模式(有缺陷,不建议使用)
package test;
/**
* @author Administrator
* 多线程变成单例模式——2
*/
public class SingletonTest {
// 类加载是创建一个对象
private static SingletonTest singleton = null;
// 私有构造方法,防止被实例化
private SingletonTest() {
}
// 获取单例对象
public static SingletonTest getInstance() {
if (singleton == null) {
synchronized (SingletonTest.class) { //同步
if (singleton == null) {
singleton = new SingletonTest();
}
}
}
return singleton;
}
}
三,同步方法(线程安全,但是比较耗性能,但是不具有 lazy 特性)
package test;
/**
* @author Administrator
* 多线程变成单例模式——3
*/
public class SingletonTest {
// 类加载是创建一个对象
private static SingletonTest singleton = null;
// 私有构造方法,防止被实例化
private SingletonTest() {
}
// 获取单例对象
public static synchronized SingletonTest getInstance() { //同步方法块
if(singleton == null){
singleton = new SingletonTest();
}
return singleton;
}
}
四,使用内部类方法(线程安全,lazy 特性)
package test;
/**
* @author Administrator
* 多线程变成单例模式——4
*/
public class SingletonTest {
// 私有构造方法,防止被实例化
private SingletonTest() {
}
/* 内部类 */
private static class SingletonFactory {
private static SingletonTest single = new SingletonTest(); // 类加载是不会执行
}
/* 获取实例对象 */
public static SingletonTest getInstance() {
return SingletonTest.SingletonFactory.single;
}
}